17

I have a use case for synchronous storage for my react native app.

Before app renders a home view, I want to check if there is a session token stored on the local storage and proceed if it is available, otherwise want to render login component instead as the initial view.

Using sync storage will simplify the code.

Joon
  • 9,346
  • 8
  • 48
  • 75
  • I used the async storage in the same situation when I developed a RN app for fun. When a token is read from the storage, I re-rendered the UI. – iplus26 Apr 28 '16 at 02:00

5 Answers5

10

I don't think there is a simple synchronous storage option. According to this answer localstorage is not implemented in the core IOS javascript engine. AFAIK the other options such as those used in this localstorage polyfill don't work. That leaves us with needing a react native module which are asynchonous by design. From the docs:

React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events

So I think Async is the way to go.

Community
  • 1
  • 1
Ryan Harmuth
  • 345
  • 2
  • 10
3

For those who are searching for this, I found this npm package that served this need

react-native-sync-localstorage

rsanath
  • 1,154
  • 2
  • 15
  • 24
1

I have a similar situation and found Realm supports synchronous read, which is what I need. Realm is a bit big for single token storage. I use AsyncStorage for everything else. Let me know if you find a simpler solution.

Jeff
  • 21
  • 4
1

If you are using development builds, you can use MMKV. It's written in C++ and is syncronous.

https://github.com/mrousavy/react-native-mmkv#expo

import { MMKV } from 'react-native-mmkv'

export const storage = new MMKV()

Set

storage.set('user.name', 'Marc')
storage.set('user.age', 21)
storage.set('is-mmkv-fast-asf', true)

Get

const username = storage.getString('user.name') // 'Marc'
const age = storage.getNumber('user.age') // 21
const isMmkvFastAsf = storage.getBoolean('is-mmkv-fast-asf') // true
moto
  • 946
  • 10
  • 27
0

There's no solution similar with Native Mobile development such as SharedPreferences in Android.

Native Way: most of the operations are synced. (such as read from storage, etc), some of the operations are async.(http request, load image)

React Native way: almost all of the operations are asynced. this is explained by @Ryan Harmuth 's answer.

So, let's start to use Redux as a solution. :)

Siwei
  • 19,858
  • 7
  • 75
  • 95