0

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).

This is my console of res:

3 Answers3

1

First, you need to update setnames because res.data is an array so you can not use res.data.name:

setnames(res.data)

And in return, you need to use map to show name:

{names.map((item) => (
    <p key={item.id}>{item.name}</p>
  ))}
Viet
  • 12,133
  • 2
  • 15
  • 21
0

res.data is an array, so if you want to only keep names, you need to map on it to only store names to your state

setnames(names => [...names, ...res.data.map(({name}) => name)])
dbuchet
  • 1,561
  • 1
  • 5
  • 7
-1

You can use useRef to set the node not to render at the first time.

Make React useEffect hook not run on initial render

Tommy Tang
  • 62
  • 3