Day 11: React Native AsyncStorage
In this post, I will talk about how to use AsyncStorage to persist data on a device in react-native. Today is Day 11 of #ReactNativeIn30Days series.
What is Asyncstorage?
From React Native official documentation, Asyncstorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app.
In simple terms, Asyncstorage is React Native’s API for storing data on a phone. It is a storage system that saves data in the form of key-value pairs. It works similar to the web browser storage API localStorage.
Why use AsyncStorage?
Asyncstorage is used in areas where you want to save user data that the application will need, whether online, offline or closed.
A typical example of its usage is when we want to manage a session. For instance, storing a user id so that the user will not always have to input his or her login credentials.
Basic actions to perform in AsyncStorage:
AsyncStorage allows one to store, retrieve, and delete data from the device storage.
Save data to AsyncStorage
To save data to AsyncStorage, we will have to call the setItem() method. This method takes in three arguments, a key, a value, and a callback function.
getItem(key:string, value, [callback]
Retrieve a value from AsyncStorage
To fetch or get a value from AsyncStorage, we call the getItem() method. It takes in two argument, a key of the item to fetch and a callback function that will be called with a result if found or an error.
getItem(key:string, [callback])
Delete data from AsyncStorage
The removeItem() method removes an item from Asynction storage by specifying the key you will want to delete or remove. This method takes in a key (the key of the item to be deleted) and a callback function upon completion
removeItem(key:string, [callback])
Wrap up:
Today we looked at how to persist data unto our phones using React Native local storage API AsyncStorage.