Most apps require that a user authenticate in some way to have access to data associated with a user or other private content. Typically the flow will look like this:
- The user opens the app.
- The app loads some authentication state from persistent storage (for example,
- When the state has loaded, the user is presented with either authentication screens or the main app, depending on whether valid authentication state was loaded.
- When the user signs out, we clear the authentication state and send them back to authentication screens.
Note: we say "authentication screens" because usually there is more than one. You may have a main screen with a username and password field, another for "forgot password", and another set for sign up.
Set up our navigators
You may not be familiar with
SwitchNavigator yet. The purpose of
SwitchNavigator is to only ever show one screen at a time. By default, it does not handle back actions and it resets routes to their default state when you switch away. This is the exact behavior that we want from the authentication flow: when users sign in, we want to throw away the state of the authentication flow and unmount all of the screens, and when we press the hardware back button we expect to not be able to go back to the authentication flow. We switch between routes in the
SwitchNavigator by using the
navigate action. You can read more about the
SwitchNavigator in the API reference.
We set the
'AuthLoading' because we will fetch our authentication state from persistent storage inside of that screen component.
Implement our authentication loading screen
Fill in other components
Auth routes are both
StackNavigators, but you could do whatever you like here. As mentioned above, you probably want your authentication route to be a stack for password reset, signup, etc. Similarly for your app, you probably have more than one screen. We won't talk about how to implement the text inputs and buttons for the authentication screen, that is outside of the scope of navigation. We'll just fill in some placeholder content.
That's about all there is to it. At the moment,
SwitchNavigator doesn't support animating between screens. Let us know if this is important to you on Canny.