Reputation: 37
I am trying to update this state that is an empty list on start:
const [winnerList, setWinnerList] = useState([]);
from a useEffect which will run once:
useEffect(()=>{
fetch("/players").then( res => res.json()).then(data => {
if(data) {
console.log(data);
setWinnerList(JSON.parse(data));
console.log(winnerList);
window.localStorage.setItem('winner', JSON.stringify(winnerList));
}
})
},[])
when I console.log (data) I get the json as expected but when I console log(winnerList) I get an empty array even though I setWinnerList with the json data.
after a
Upvotes: 1
Views: 69
Reputation: 1444
This is because setWinnerList
is asynchronous. You can change the logic like this :
useEffect(() => {
fetch("/players").then(res => res.json()).then(data => {
if (data) {
console.log(data);
setWinnerList(JSON.parse(data));
}
})
}, []);
useEffect(() => {
console.log(winnerList);
window.localStorage.setItem('winner', JSON.stringify(winnerList));
}, [winnerList]);
First winnerList
should be updated, and after the new render has been occured, useEffect
callback with winnerList
dependency gets called.
Check out react documentation about useEffect and useState and also there are a bunch of very good examples in beta.reactjs about useEffect hook.
Upvotes: 4