The React Native docs (https://facebook.github.io/react-native/docs/asyncstorage.html) says:
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.
I doesn't understood why it recommends I write an abstraction just because it operates globally.
It makes sense to use it only for light things, but why is operating globally a bad thing?
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.
React Native AsyncStorage is a simple, unencrypted, asynchronous, persistent, storage system which stores the data globally in the app. It store data in the form of a key-value pair. React Native recommended to use abstraction on top of AsyncStorage instead of AsyncStorage directly as it operates globally.
Note that on Android AsyncStorage has an upper size limit of 6MB.
Using the setItem() method The setItem method saves data to the AsyncStorage and allows a key and a value. Here, the key is a string that the data or value is assigned to: // React Native component const value = { name: "Chimezie", job: "Software Developer" }; const storeUser = async () => { try { await AsyncStorage.
Think of AsyncStorage
items like global variables, so every time you add something or read something you're accessing a global. This might make sense for something like an API base URL, but for most other things it'll start to get messy.
Imagine you need to store information about users, you might reasonably start with their name, so you add name
to Async. Later you realise you want their DOB
, then maybe their pets
and so on. If you create these globally you're also going to be accessing them using variable names such as name
- which in the global context start to lose meaning. Further, you'd have to write:
AsyncStorage.getItem('name', (err, result) => {
this.setState({
name: result
})
})
All over your project - in the future if the variable name name
changes, you'll have to update it across all files.
Instead you'd be better of writing a User
class, which would provide instance variables (or some such), and which could then serialise themselves into Async. Further you could then swap out the storage mechanism with ease if the project later became backed by an API, or required a more powerful database-style storage system.
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