I'm currently playing with ways to change state within an onPress event in React-Native and haven't had much luck. When somebody presses the "Change State?" option in the summoned alert, I would want to change the state to true
. However, when calling setState()
or a useCallback()
which toggles the state, it continues to print false printed (twice).
FYI: I call the alert as ExampleAlert()
rather than <ExampleAlert />
elsewhere in my code.
Does this issue have something to do with the way the Alerts are written in RN, or the fact that Alerts do not trigger a re-render?
const [state, setState] = useState(false);
const changeStateCallback = useCallback(() => {
setState(!state);
}, [state]);
const ExampleAlert = () => {
Alert.alert(
'Title',
'Message',
[
{
text: 'Change State?',
onPress: () => {
changeStateCallback;
console.log(state);
setState(true);
console.log(state);
},
},
{
text: 'OK',
onPress: () => {},
},
],
);
return null;
};
CodePudding user response:
useState is async, you can not see the change in the same enviroment
so you just need do this:
onPress: () => {
setState(true);
},
or
const handlePress =()=>{
setState(true);
}
onPress: () => { handlePress },
this syntax () => { }
does not execute yet, it's executed when the user clicked over that.
edit 1:
const handlePress =()=>{
setState(true);
console.log(state) // here you can not see the change
}
console.log(state) //put your console outside of handlePress to see the change
CodePudding user response:
I think I know your problem.
console.log()
is a synchronous function, setState()
is an async one, called async code won't run until all what's in the current call stack finishes running.
You won't see changes in state until later on.
Have you tried visualizing state with debugging tools?
Similar question: Console.log() after setState() doesn't return the updated state