Async SetState on componentDidMount () alert in React Native

The warning message says:

"Warning. Can only update a mounted or mount component. This usually means that you are calling setState, replaceState, or forceUpdate on a disabled component. This is a non-op.

The code caused this:

async componentDidMount() {
  const token = await AsyncStorage.getItem('google_token');

  if (token) {
    this.props.navigation.navigate('feed');
    this.setState({ token });
  } else {
    this.setState({ token: false });
  }
 }

      

After some google, I am really confused if I bother with this warning. How can I get a warning message without disabling a rule like this Github question suggested?

+3


source to share


1 answer


I think the problem is that you go to the "feed" and then update the state of that component. It might be better to update the state first and then move on after it completes:



async componentDidMount() {
  const token = await AsyncStorage.getItem('google_token');

  if (token) {
    this.setState({ token }, () => this.props.navigation.navigate('feed'));
  } else {
    this.setState({ token: false });
  }
 }

      

+7


source







All Articles