React Native: Persistent User Login

Nicolas M. Toscano
3 min readSep 25, 2015

--

TL;DR: Use AsyncStorage

WARNING: On iOS (RN v0.28), AsyncStorage saves key-value pairs as a plaintext JSON file in the Documents directory. Do not use AsyncStorage for storing sensitive data. (Thank you Ariel Elkin for pointing this out)

This is a barebones codebase implementing persistent user login using Tokens. You can find the whole file here. This walkthrough assumes you have already completed the Facebook React Native tutorial.

Additionally, there is ES6 sprinkled throughout this walkthrough to make use of the lexical scoping. You can read more about that here

The key thing to notice here is AsyncStorage. This component is comparable to localStorage in the browser.

Next we’re going to create the React Native logic inside of the React.createClass method call.

The first method we’re going to create is getInitialState. Crafting this method first, or at least near the top of the React class, is generally good practice.

This will set all state values we’ll be listening for to falsy values that we’re later going to change.

Assuming that your UI calls “submitCredentials” when the user hits the “login” button and passes the user object along, this is more or less how you’re going to want to organize this bit of logic.

The key thing to notice here is how we’re using AsyncStorage.multiSet to set both the token and userId into storage.

If you were to incorporate the Flux data flow architecture, the lines following storing the user in AsyncStorage would be a good place to store the user data in the Dispatcher. However, Flux is outside the scope of this walkthrough.

Next we’re going to construct componentWillMount:

This method should be placed near the top of the class, along side getInitialState.

componentWillMount invokes immediately before the initial rendering occurs.

The key thing to notice here is how we retrieve the user and token from AsyncStorage, if they’re there. Once the user logs in, each time they visit this component, they should be automatically logged in. The getUser function should look something like this:

We want to retrieve our full user object from the server side. Previously we only had our user’s username and password.

Once we retrieve the info from storage, we then change the user and token state which trigger a re-render (This happens in componentWillMount). Your render function should look something like this:

But wait! One last thing, we have to give the user a way to logout.

And that should be it. Leave a comment if you feel I left anything out, have questions, or just want to say hi.

--

--