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;
};