I am learning React.js and got problem in a place.
I am fetching data from localhost:4000/products (i.e)
Here is my localhost:4000/products page
And I am doing the backend query in node.js
Here is the page:
const express = require('express');
const app = express();
const cors = require("cors");
const mysql = require("mysql");
app.use(cors());
const selectallquery = "SELECT * FROM users";
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "Sakthi@1234",
database: "reactSql",
});
app.get("/",(req,res)=> {
res.send('Hello Sakthi')
});
app.get("/products/add", (req,res)=> {
const { name } = req.query;
console.log(name);
const insertquery = `INSERT INTO users (name) VALUES ('${name}')`;
db.query(insertquery, (err,result)=> {
if(err){
return res.send(err)
}
else{
return res.send("Successfully added...`")
}
});
});
app.get("/products", (req,res)=> {
db.query(selectallquery, (err,result)=> {
if (err){
return res.send(err)
}
else{
return res.send(result)
}
});
});
app.listen(4000,()=> {
console.log("Running on server 4000")
});
And here is my React.js page:
import React, { useState, useEffect } from 'react'
import axios from "axios";
function Login() {
const [names, setnames] = useState([])
useEffect(()=> {
axios.get("http://localhost:4000/products")
.then(res => {
if (res !== ""){
setnames([...names,res.data.name])
}
})
.catch(err => {
console.log(err)
})
},[])
return (
<div>
{
names
}
</div>
)
}
export default Login
The state names is not set with any value. And it is not showing any values:
Its the page showing nothing :(
And Also i want to know how to make the useEffect hook not to render on first render(componentWillMount) and only to render at last(componentDidMount).