This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Persist Items with React Native AsyncStorage

1:06 React lesson by

In this lesson we'll use AsyncStorage to save our items so they persist with each reload of the application. We'll show how to use the promise base interface to handle success as well as handle errors.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

In this lesson we'll use AsyncStorage to save our items so they persist with each reload of the application. We'll show how to use the promise base interface to handle success as well as handle errors.

We'll start by importing AsynchStorage from React native. Now, we'll create the componentWillMount lifecycle method, we'll then call asynchstorage.getItem, pass in the key of "items" to gather, which returns promise of then, which takes a function.

It then passes in a string of jason, we'll call try and catch the error. We need this in case our JSON is unparsable, we'll say const items = JSON.parse(json); then, call this.setSource(items, items).

Now, we'll scroll down to our setSouce, and because all of our calls go through setSource, we can say asynchStorage.setItem(items) and then JSON.Stringify the items that we get passed in.

Now, if we go and we refresh our emulator, you can add an item, refresh again, and there it is.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?