javascriptiosreact-nativenpmstack-navigator

How to change screen and setState at the same time on first click in React Native


I have a function that changes the screen and sets the state at the same time that works given below (initial state of weapon is null):

var { navigate } = this.props.navigation;
  clickM16 = () => {
      this.setState({
        weapon: "M16"
      });

      navigate("Second", {weapon: this.state.weapon});

  }

And I am calling this on my second screen via {this.props.navigation.state.weapon}, but the state doesn't seem to update to M16 until I go back and click the button again.

I have console logged both above and below the setState function and on the first click it always gives me null but M16 when I go back and click it again.

Can I not run setState at the same time as navigating between screens? If I can what am I doing wrong.

TLDR: I'm trying to set state and change page in same function so I can then display the new state on the new page as text. The state change doesn't happen until the second click of the button.


Solution

  • Try putting a small timeout for the navigate. The state change may not be complete when you hit the navigate instruction

    var { navigate } = this.props.navigation;
     clickM16 = () => {
      this.setState({
        weapon: "M16"
      });
    
      setTimeout(() => navigate("Second", {weapon: this.state.weapon}),20);
    
    }