0

React JS component:

Here I make a request to the backend to retrieve some data stored in mysql table. It returns the row as array of objects. So, I store them in a state favcoin. When I console.log(favcoin) , it just shows me and empty array [ ] like this. But if I console.log(response.data) it shows the result correctly.

import Axios from 'axios'
import { useEffect,useState } from 'react'

const Favourite=()=> {
const [favcoin,setFavcoin]=useState([])

//Getting all the favorites

  useEffect(() => {
    Axios.post('http://localhost:9000/getFav',
    { userid : localStorage.getItem('userid') }
      ).then(
        (response)=>{
          setFavcoin(response.data)
          console.log(favcoin)
       }
    )
  }, [])
return (
    
)
}
export default Favourite;

Here's my piece of backend code (node js) where I connect to, from the react component

//Getting all Favorites of user
app.post('/getFav',(req,res)=>{

const user=req.body.userid;
db.query(`select * from favorite where userid=?;`,[user],(err,result)=>{
        res.send(result);
})
})

I am clueless. I am stuck at this point. Actually I have stored array of objects before in state from APIs. But now for some reason I can't. Any help is appreciated. Thank you

2 Answers2

-1

i think Your code is right. so by the time you calling console log the value is not ready yet, beacuse useState works asynchronously. but that wont be a issue if you show that data in the html

Basically, react does not change the state immediately, see useState set method not reflecting change immediately

If you want to see that the state is really changed, try to render favcoin,

... return (
        <div>{JSON.stringify(favcoin)}</div>
    )

or you can use chrome react dev tools aswell

yasith rangana
  • 196
  • 2
  • 12
-2

Because setState is asynchronous. You need to console log your state value outside of the useEffect, like this,

import Axios from 'axios'
import { useEffect,useState } from 'react'

const Favourite=()=> {
const [favcoin,setFavcoin]=useState([])

//Getting all the favorites

  useEffect(() => {
    Axios.post('http://localhost:9000/getFav',
    { userid : localStorage.getItem('userid') }
      ).then(
        (response)=>{
          setFavcoin(response.data)
       }
    )
  }, []);

console.log(favcoin);

return (
    <span>{JSON.stringify(favcoin)}</span>
)
}

export default Favourite;

Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30