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