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..
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..
I always use/create a wrapper modulee around AsyncStorage, utilising JSON.parse & JSON.stringify on the data coming in and out.
This way you remove the need to have you JSON.parse & JSON.stringify calls inside your business logic. This keeps the code a bit nicer on the eye.
Something like
I have set value in "name" key in AsyncStorage
To get value from key "name"
You can only store strings, but you can totally stringify objects and arrays with JSON, and parse them again when pulling them out of local storage.
This will only work properly with plain
Object
-instances or arrays, though.Objects inheriting from any prototype might cause some unexpected behaviour, as prototypes won't be parsed to JSON.
Booleans (or any primitive for that matter) can be stored using
JSON.stringify
, though.JSON recognises these types, and can parse them both ways.
So:
After getting and parsing the value (which does not have to be a boolean, it can be an object. Whichever satisfies your needs), you can set in to the state or do whatever with it.
Based on the AsyncStorage React-native docs, I'm afraid you can only store strings..
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 :