1

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;
  };
CosmicCat
  • 612
  • 9
  • 19

2 Answers2

1

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
rnewed_user
  • 1,386
  • 7
  • 13
  • Did not solve my problem. I used these solution as well as a useCallback() and it continues to print false unfortunately – CosmicCat Nov 03 '21 at 17:33
  • @CosmicCat you dont have problem, just you can not see the change in the same enviroment, put your console outside – rnewed_user Nov 03 '21 at 19:35
  • Yep I understand that. However, when I do console.log(state) later on it still prints false – CosmicCat Nov 03 '21 at 20:00
0

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