I need some help in creating a pie chart in react for the data retrieved from mysql database.
App.js code :
import React , { PureComponent } from 'react';
import {useState , useEffect } from 'react';
import './App.css';
import { PieChart , Pie , Tooltip } from "recharts";
function App() {
const [category, setCategory] = useState([]);
useEffect(()=>{
const getDbData = async ()=>{
const getA = await fetch('http://localhost:3001/posts/');
const getData = await getA.json();
setCategory(getData);
console.log(getData);
// console.log(data);
}
getDbData();
},[])
return (
<div className="App">
<h1>Hello World!!</h1>
<h2>My PieChart</h2>
<PieChart width={400} height={400}>
<Pie dataKey="value" isAnimationActive={false}
data={category}
cx="50%" cy="50%" outerRadius={80} fill="#8884d8"
label
/>
<Tooltip />
</PieChart>
</div>
);
}
export default App;
Also I have installed all the dependencies required but still pie chart is not created for the data which I have fetched from database.
Server.js :
const express = require("express");
const app = express();
const mysql = require('mysql');
const cors = require('cors');
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user : 'root',
host : 'localhost',
password : 'password',
database : 'lab',
});
db.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.get('/posts', (req, res) => {
db.query("SELECT empname , empage FROM employee;", (err, results, fields) => {
if(err) throw err;
res.send(results);
});
});
app.listen(3001 ,(error)=>{
if (error) throw error ;
console.log("Server is running on port 3001");
})
When I hardcode data and try to display in pie chart then it works But it is not working when I am trying to display the data which I have fetched from database.
Related
I'm trying to upload csv file into mysql workbench, what I'm trying to figure out is when I upload the csv file, the first column of the excel will be the header of the table in workbench.
Front end
const Home = () => {
const [file, setFile] = useState(null);
const handleFileInput = (event) => {
setFile(event.target.files[0]);
};
const handleUpload = async () => {
const formData = new FormData();
formData.append("file", file);
try {
const res = await fetch("http://localhost:5000/api/upload", {
method: "POST",
body: formData,
});
const data = await res.json();
console.log(data);
} catch (error) {
console.error({message:error.message});
}
};
return (
<div>
<input type="file" onChange={handleFileInput} />
<button onClick={handleUpload}>Upload</button>
</div>
)
}
export default Home
index.js
import express from 'express';
import cors from 'cors';
import mysql from 'mysql2/promise';
import csv from 'csv-parser'
const PORT = 5000
const app = express();
app.use(express.json());
app.use(cors())
app.post('/api/upload', async (req, res) => {
const { file } = req.files;
const results = [];
try {
const connection = await mysql.createConnection({
host: "localhost",
user: "root",
password: "admin",
database: "e-learning"
});
fs.createReadStream(file.path)
.pipe(csv())
.on("data", (data) => results.push(data))
.on("end", async () => {
const columns = Object.keys(rows[0]).map(column => `\`${column}\` VARCHAR(255)`);
const tableName = `${filePath}`;
const createTableSql = `CREATE TABLE \`${tableName}\` (${columns.join(", ")})`;
await connection.query(createTableSql);
const insertDataSql = `INSERT INTO \`${tableName}\` (${Object.keys(rows[0]).map(column => `\`${column}\``).join(", ")}) VALUES ?`;
const data = rows.map(row => Object.values(row));
await connection.query(insertDataSql, [data]);
console.log(`Table "${tableName}" created and data inserted successfully.`);
});
} catch (error) {
console.log(error)
}
})
app.listen(PORT, () =>{
console.log(`Listening to port http://localhost:${PORT}`)
})
This is the error i'm receiving
I am new to MySQL, and I am having difficulties in getting my data from MySQL database.
import express from 'express';
import mysql from 'mysql';
const app = express();
const db = mysql.createConnection({
host:"localhost",
user:"root",
password:"2000",
database: "test"
})
app.get('/', (req, res) => {
res.json('hello this is backend')
})
app.get('/books', (req, res) => {
const q = "SELECT * FROM books"
db.query(q, (err, data) => {
if(err) {
return res.json(err)
}
else{
return res.json(data)
}
})
})
app.listen(8800, () => {
console.log('Connected to backend server...');
});
as it gives following error on localhost:8800/books/
{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
any help would be valuable :)
I am trying to create a React Native app that can access and display movie showtime data from a MySQL database that I have stored on linode. I have a server.js file set up that looks like this:
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createConnection({
host: '<host ip>',
user: '<user>',
password: '<password>',
database: 'filmscrapedb',
});
const app = express();
app.get('/FilmShowings', function (req, res) {
connection.connect();
connection.query('SELECT * FROM FilmShowings', function (error, results, fields) {
if (error) throw error;
res.send(results);
});
connection.end();
});
// Start the server
app.listen(3000, () => {
console.log('Go to http://localhost:3000/FilmShowings to see FilmShowings');
});
Running this, I can see my data at the localhost address:
[{"title":"The Night of the Hunter","showtime":"5:00 pm","date":"Sep 9","location":"Row House Cinema","buy_ticket_link":"https://rowhousecinema.com/purchase/344799/","summary":"Based on a true story out of nearby Clarksburg, West Virginia, this Robert Mitchum noir is a nightmarish fairytale thriller about a serial killing preacher in the deep south. Mitchum keeps you on the edge of your seat as he hunts two young children who know the location of a stash of money hidden by their real father."}
...etc
However, I am stumped on how to fetch this data into React Native. I have attempted to adapt the function component example from React Native's docs, like so:
import React, {useState, useEffect} from 'react';
import {ActivityIndicator, FlatList, Text, View} from 'react-native';
const App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
const getMovies = async () => {
try {
const response = await fetch('http://localhost:3000/FilmShowings');
const json = await response.json();
setData(json.FilmShowings);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
useEffect(() => {
getMovies();
}, []);
return (
<View style={{flex: 1, padding: 24}}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={data}
keyExtractor={({id}, index) => id}
renderItem={({item}) => (
<Text>
{item.title}, {item.location}
</Text>
)}
/>
)}
</View>
);
};
export default App;
...but this is clearly incorrect, as I am getting an error of [TypeError: Network request failed]. Any suggestions on what I am doing wrong here would be greatly appreciated.
I want to display the name of the user that i have stored in my database. I am not able to retrieve any values. There is doesn't seem to be any error. I think i am not able to correctly access the database, But i can't figure out where i going wrong.
This is my react native code.
export default class UserProfile extends Component{
constructor(props)
{
super(props);
this.state={
name:'',
email:'',
}
};
componentWillMount() {
return this.getUser()
}
getUser(){
return fetch('http://192.168.0.20:3000/userprofile',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
}
body: JSON.stringify({
name: this.state.name,
})
})
.then((response) => response.json())
.then((responseData) => {})
}
render(){
console.disableYellowBox = true; //// to disable warning :)
return(
<Text> Username:{this.state.name}</Text> // trying to display name here.
);
}
}
This is my back-end code.
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database:'backend',
})
/* our backend endpoint to check for users ian the database */
router.post('/', function(req, res, next) {
var name=req.body.name;
var phone=req.body.phone;
var email = req.body.email;
var password = req.body.password;
connection.query("SELECT * FROM user WHERE email = ? ",[email],function(err,row,fields){
console.log(name);
if (err) console.log(err);
});
});
module.exports = router;
I want to get the data from front end react js form and insert in to mysql database using backend express. Can you tell me the flow from front end to backend with simple one field form using react js and then insert into database.
Lets take an example of a simple library application having table(books) with fields book_name and author .
Lets see the Backend Code First(in Node Js)
const express = require('express');
const bodyParser = require('body-parser');
var connection = require('express-myconnection');
var mysql = require('mysql');
const app = express();
app.use(bodyParser.json());
app.use(
connection(mysql,{
host: 'localhost', //'localhost',
user: 'userEHX',
password : 'hMmx56FN4GHpMXOl',
port : 3306, //port mysql
database:'sampledb'
},'pool')); //or single
app.post('/add_book',(req,res)=>{
let {book_name,author,} = req.body;
if(!book_name) return res.status(400).json('Book Name cant be blank');
if(!author) return res.status(400).json('Author cant be blank');
var data={book_name:book_name,
author:author};
var query = connection.query("INSERT INTO books set ? ",data,
function(err, rows)
{
if (err){
//If error
res.status(400).json('Sorry!!Unable To Add'));
console.log("Error inserting : %s ",err );
}
else
//If success
res.status(200).json('Book Added Successfully!!')
});
});
app.listen(3000, ()=> {
console.log(`app is running on port 3000`);
});
Now Let's see the Front End code on React Js:
import React from 'react';
export default class AddBook extends React.Component {
constructor(){
super();
this.state = {
bookname:'',
author:'',
};
}
updateInfo = (event) =>{
let fieldName = event.target.name;
let fieldValue = event.target.value;
if(fieldName === 'bookname') {
this.setState({bookname: fieldValue});
}
else if(fieldName === 'author'){
this.setState({author:fieldValue});
}
};
addBook=(e)=>{
let {bookname,author}=this.state;
fetch('localhost:3000/add_book', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
bookname:bookname,
author:author,
})
}).then(response=>response.json()).then(data=>{
window.alert(data)
//Do anything else like Toast etc.
})
}
render(){
return(
<div className="add_book">
<div>
<label>Book Name</label>
<input onChange={this.updateInfo} name="bookname" value{this.state.bookname}/>
</div>
<div>
<label >Author</label>
<input onChange={this.updateInfo} name="author" value={this.state.author}/>
</div>
<button onClick={this.addBook}>Add</button>
</div>
)
}
}
Here's a simple example that establishes a connection to mysql.
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'dbuser',
password : 's3kreee7',
database : 'my_db'
});
connection.connect()
connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
if (err) throw err
console.log('The solution is: ', rows[0].solution)
})
connection.end()
Helpful guide to integrate popular Node.js modules for DBs
**On REACT**
import React, { Component } from 'react';
import axios from "axios";
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from "react-router-dom";
import createHistory from "history/createBrowserHistory"
//import isLoggedIn from '../../helpers/is_logged_in';
class Login extends Component {
constructor(props) {
const history = createHistory();
super(props);
// this.islogin = this.islogin.bind(this);
this.signIn = this.signIn.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.state = {
email:'',
password:'',
redirectToReferrer: false
};
}
signIn(){
const history = createHistory()
const location = history.location;
console.log(location);
// alert(this.state.email);
axios.post('http://192.168.1.35:3012/users', {
email: this.state.email,
password: this.state.password
})
.then(function (response) {
// console.log(response.data[0].id);
// console.log(response.data.email);
var das = localStorage.setItem('sessionid', response.data[0].id);
var das = localStorage.setItem('myData', response.data[0].name);
var da = localStorage.getItem('myData');
var myid = sessionStorage.setItem('myid', response.data[0].id);
//alert(da);
//history.go('/dash');
})
.catch(function (error) {
console.log(error);
});
this.setState({ redirectToReferrer: true });
}
handleEmailChange(e){
this.setState({email:e.target.value})
}
handlePasswordChange(e){
this.setState({password:e.target.value})
}
render() {
console.log('11111');
const myid = sessionStorage.getItem('myid');
const { from } = this.props.location.state || { from: { pathname: "/dash" } };
const { redirectToReferrer } = this.state;
if (redirectToReferrer || myid !=null) {
console.log('22222');
return <Redirect to={from} />;
}
else{
return (
<form className="form-signin" history={this.props.history}>
<h2 className="form-signin-heading"> Please sign in </h2>
<label className="sr-only"> Email address
</label>
}
<input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required />
<label htmlFor="inputPassword" className="sr-only"> Password</label>
<input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />
<button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button">Sign in</button>
</form>
);
}
}
}
export default withRouter(Login);
**On Express**
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var fs = require('fs');
var formidable = require('formidable');
var busboy = require('connect-busboy');
var cors = require('cors')
var router = express.Router();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'test',
database : 'example'
});
connection.connect(function(err) {
if (err) throw err
// console.log('You are now connected...')
})
/* POST users listing. */
router.post('/', function(req, res, next) {
console.log(req.body.email);
user_sql = "INSERT INTO table_name VALUES (req.body.name, req.body.password);
console.log(user_sql)
connection.query(user_sql, function (err, rows, fields) {
if (err) throw err
console.log(rows)
res.end(JSON.stringify(rows));
// res.json(rows);
});
});
module.exports = router;