Persist Items with React Native AsyncStorage

Jason Brown
InstructorJason Brown
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

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.

[00:00] 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.

[00:20] 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).

[00:43] 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.

[01:00] Now, if we go and we refresh our emulator, you can add an item, refresh again, and there it is.

egghead
egghead
~ 3 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today