React Native provides the AsyncStorage
library as a way to store persistent data in RN apps. In general, AsyncStorage is pretty straightforward to use, except for one aspect:
Both of the main AsyncStorage
functions, AsyncStorage.getItem
and AsyncStorage.setItem
return Promise
s. This is simple enough to understand: The actual querying or saving done by the function runs in the background, and the getting or saving of items might fail, requiring us to catch
the error.
However, it seems that nowhere in the React Native documentation is it specified what, exactly, are the failure cases of AsyncStorage
or which errors one should expect when calling setItem
or getItem
. Of course, one can deduce what might be a few of the error cases: One might try to getItem
using an inexistent key, or one might try to setItem
in a full or nearly full store, and the OS might refuse to release more disk space for your app, but it is frustrating not to have a full list.
It would be nice to know how exactly AsyncStorage
might fail, so that people who are developing React Native apps which use data persistence might know exactly which failure cases they need to handle.
AsyncStorage is a simple, asynchronous, unencrypted by default module that allows you to persist data offline in React Native apps. The persistence of data is done in a key-value storage system. There are numerous scenarios where this module can be beneficial.
Current Async Storage's size is set to 6MB. Going over this limit causes database or disk is full error. This 6MB limit is a sane limit to protect the user from the app storing too much data in the database.
AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage. It is recommended that you use an abstraction on top of AsyncStorage instead of AsyncStorage directly for anything more than light usage since it operates globally.
AsyncStorage is also asynchronous, meaning that its methods run concurrently with the rest of your code, and it's persistent, meaning that the stored data will always be available globally even if you log out or restart the application.
The code is open source, you can see when the calls fail, for example here on android or here for ios.
The getItem
call, fails, for example when requiring a nonexistent item. Other example may be Failed to create storage directory.
which you can see in the ios module (for example when there's not enough space on device).
According to the documentation of react-native-community/async-storage
,getItem
won't fail when requiring a nonexistent item, it will just return null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With