React Native AsyncStorage storing values other than strings

Hasen picture Hasen · Feb 24, 2016 · Viewed 39.5k times · Source

Is there any way to store values other than strings with AsyncStorage? I want to store simple boolean values for example.

AsyncStorage.setItem('key', 'ok');

Is no problem, but:

AsyncStorage.setItem('key', false);

Does not work..

Answer

G. Hamaide picture G. Hamaide · Feb 24, 2016

Based on the AsyncStorage React-native docs, I'm afraid you can only store strings..

static setItem(key: string, value: string, callback?: ?(error: ?Error)
> => void) 

Sets value for key and calls callback on completion, along with an Error if there is any. Returns a Promise object.

You might want to try and have a look at third party packages. Maybe this one.

Edit 02/11/2016

Thanks @Stinodes for the trick.

Although you can only store strings, you can also stringify objects and arrays with JSON to store them, then parse them again after retrieving them.

This will only work properly with plain Object-instances or arrays, though, Objects inheriting from any prototypes might cause unexpected issues.

An example :

// Saves to storage as a JSON-string
AsyncStorage.setItem('key', JSON.stringify(false))

// Retrieves from storage as boolean
AsyncStorage.getItem('key', (err, value) => {
    if (err) {
        console.log(err)
    } else {
        JSON.parse(value) // boolean false
    }
})