Why the React Native docs recommends that you use an abstraction on top of AsyncStorage?
Asked Answered
R

1

14

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?

Roeder answered 1/6, 2016 at 8:24 Comment(0)
F
17

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.

Flouncing answered 1/6, 2016 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.