Handling logout properly with React Native

Viewed 29082

I have a react native application that show's different navigators based on whether or not there is an authenticated firebase user.

Here's my main App class:

export default class App extends Component {
  state = { loggedIn: null }

  componentWillMount() {
    firebase.initializeApp({...});

    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ loggedIn: true });
      } else {
        this.setState({ loggedIn: false });
      }
    });
  }

  renderContent() {
    switch (this.state.loggedIn) {
      case true:
        return (
          <MenuContext>
            <MainNavigator />
          </MenuContext>
        );
      case false:
        return (
          <AuthNavigator />
        );
      default:
        return (
          <View style={styles.spinnerStyle}>
            <Spinner size="large" />
          </View>
        );
    }
  }

  render() {
    return (
      <Provider store={store}>
        {this.renderContent()}
      </Provider>
    );
  }
}

Now this works perfectly fine with re-rendering the correct Navigator when a user logs in.

The problem I have is with logging out. In my MainNavigator (the one that shows when a user is logged in), I have a logout button which logs the user out. Implemented like this:

signOutUser = async () => {
    try {
        await firebase.auth().signOut();
    } catch (e) {
        console.log(e);
    }
}

render() {
    return (
        ...
        <Button title="logout" onPress={() => this.signOutUser()} />
    )
}

This does what is expected, however, I get the following warning which I want to resolve:

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState or forceUpdate on an unmounted component. This is a no-op.

What is the best practice way of implementing this logout functionality?

Edit: I'm using the react-navigation library for managing my application navigation.

1 Answers
Related