Home > front end >  React Native, Stale Closures when updating a state
React Native, Stale Closures when updating a state

Time:08-15

I have an issue with the states not updating properly (stale closure). I am first setting index 0 of activeCards and console logging it (the first entry in the log provided). This log returns the result of the state as it was prior to it being updated. Then I am setting index 1 of the same and console logging it (second entry in the log provided). The second log returns the result as it was prior to the second update (ie as it should've been logged after the previous update). How can I update a state immediately or else wait for it to be updated before I proceed?

useEffect(() => {
    console.log(activeCards)
  }, [activeCards])

if(condition){
        temp = [...activeCards];
        temp[0] = {index: index, url: cards[index]};
        setActiveCards([...temp])
        console.log(activeCards)
}
else{

        temp = [...activeCards];
        temp[1] = {index: index, url: cards[index]};
        setActiveCards([...temp])
        console.log(activeCards)
}

enter image description here

CodePudding user response:

let temp = [activeCards];

This makes temp a 2d array since activeCards itself is an array. Maybe what youre intending to do is,

let temp = [...activeCards];

CodePudding user response:

state not update immediately for performance. if you use functional component you can use the useEffect(()=>{//code run after state updated},[your state]) and it call every time your state update to new value. and if you are using class component you can use this.setState({someState:''}, () => { //code run after state updated });

CodePudding user response:

You can do like this.

    useEffect(() => {
    console.log(activeCards);
}, [activeCards]);

let temp = [...activeCards];
temp[0] = { index: index, url: cards[index] };
if (!condition) {
    temp[1] = { index: index, url: cards[index] };
}
setActiveCards([...temp]);
  • Related