AsyncStorage
AsyncStorage — Is React Native’s API for storing data persistently over the device.
Can prove very helpful when we want to save data that the application would need to use, even when the user has closed it or has even closed the device.
- It’s a storage system that developers can use and save data in the form of key-value pairs.
- AsyncStorage API is asynchronous, so each of its methods returns a Promise object and in case of error, an Error object. It’s also global, so use it with caution.
- It is not a replacement for state data and it should not be confused with that; besides, state data will be erased from memory when the app closes.
- It is recommended that you use an abstraction on top of AsyncStorage instead of AsyncStorage directly.
Basic actions to perform in AsyncStorage
- Set an item, along with its value.
- Retrieve an item’s value.
- Remove an item.
Save to AsyncStorage
Retrieve value from AsyncStorage
Additional information
- In this case, we only need the string key to refer to the AsyncStorage needed item. In case userId key does not exist in AsyncStorage (i.e. the first time the app loads), the function will return undefined or in the example above the string 'none'.
Const getUserId = async () => {
let userId = '';
try {
userId = await AsyncStorage.getItem('userId') || 'none';
} catch (error) {
// Error retrieving data
console.log(error.message);
}
return userId;
}
Delete from AsyncStorage
Const deleteUserId = async () => {
try {
await AsyncStorage.removeItem('userId');
} catch (error) {
// Error retrieving data
console.log(error.message);
}
}
Usage with state manager
When we use a state manager within our apps (i.e. Redux — or new React’s context API), it is a really good idea to abstract the related AsyncStorage code within the state manager code, instead of “overloading” the screen’s component code.
Example with Redux
// packages
import {AsyncStorage} from 'react-native';
const initialState = {
id: null,
sessionId: null,
username: null,
password: null
};
export default (state = initialState, action) => {
switch (action.type) {
case 'SAVE_USER':
// save sessionId & userId in AsyncStorage
if (action.user.sessionId) {
AsyncStorage.setItem('sessionId', action.user.sessionId);
}
if (action.user.id) {
AsyncStorage.setItem('userId', action.user.id);
}
return {
...state,
id: action.user.id || state.id,
sessionId: action.user.sessionId || state.sessionId,
username: action.user.username || state.username,
password: action.user.password || state.password
});
default:
return state;
}
};