0

I'm trying to update a state as soon as the page comes to focus in react native with react native navigation, but if I log the value it still results in the old one.

useFocusEffect(
    React.useCallback(() => {
      if (route.params?.key !== null) {
        setKey(route.params?.key);
        console.log(route.params?.key)              //These two console log give different values
        console.log(key);
        setLastTokenDate(route.params?.date);
      }
      
    }, [route.params?.chiave, route.params?.data]),
  );
  • 1
    That is architectural decision, the behavior is described in the documentation, there are many similar questions on stackoverflow [1](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) and [2](https://stackoverflow.com/questions/62900377/why-is-react-setstate-hook-not-updating-immediately) and [3](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately), there is also a detailed description on the [github](https://github.com/facebook/react/issues/11527). – Sergey Sosunov Feb 03 '23 at 16:46

1 Answers1

1

Try this:

useFocusEffect(
React.useCallback(() => {
if (route.params?.key !== null) {
setKey(route.params?.key);
setLastTokenDate(route.params?.date);
}
}, [route.params?.key, route.params?.date]),
);

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

I think you will find where is your mistake