Reputation: 249
I made a custom node API which fetch the data of students from database.
And I connect it to react and try to fetch data and display. but I am facing an issue that I get data from API But when I try to set the data which I got from api response and try to console my useState()
variable i.e. apiData
it gives me undefined.
Below is my code:
const [apiData,setApiData] = useState([])
const url ="http://localhost:5000/student/"
useEffect(() =>{
fetch(url).then(
(response) =>{
return response.json()
}
).then((data) =>{
console.log(data);
setApiData(...data)
console.log(apiData)
})
},[])
console.log(data)
gives me [{…}, {…}, {…}, {…}, {…}, {…}]
console.log(apiData)
gives me []
Upvotes: 0
Views: 102
Reputation: 489
In order to view/use a state value immediately after loading it/ changing its value, you need to use it inside the callback of the set
hook.
Here, your state apiData
was loaded with the value of data
and you tried to access it immediately after it was set.
Also you are trying to spread an object array inside a state directly, which isn't right.
This is how you can preview the updated state: setApiData(data, () => console.log('New Data values:'+apiData))
Upvotes: 0
Reputation: 56
I believe this answers your question. I’ve updated the state, but logging gives me the old value.
Calling the set function does not change state in the running code. Updating state requests another render with the new state value, but does not affect the apiData
JavaScript variable in your already-running event handler.
Upvotes: 1
Reputation: 501
const [apiData,setApiData] = useState([])
const url ="http://localhost:5000/student/"
useEffect(() => {
if(apiData){
console.log(apiData);
}
},[apiData])
useEffect(() =>{
fetch(url).then(
(response) =>{
return response.json()
}
).then((data) =>{
console.log(data);
setApiData(...data)
console.log(apiData)
})
},[])
Try writing your console.log in useEffect as shown above in the code.
Upvotes: 0