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..
To store value in local storage in React Native, we can use AsyncStorage. to call AsyncStorage. setItem with the key and value to storage the entry with the key and value. Then we call AsyncStorage.
I suggest you use react-native-easy-app, through which you can access AsyncStorage synchronously, and can also store and retrieve objects, strings or boolean data.
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 } })
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.
JSON.stringify(false) // "false" JSON.parse("false") // false
So:
// Saves to storage as a JSON-string AsyncStorage.setItem('someBoolean', JSON.stringify(false)) // Retrieves from storage as boolean AsyncStorage.getItem('someBoolean', function (err, value) { JSON.parse(value) // boolean false } // Or if you prefer using Promises AsyncStorage.getItem('someBoolean') .then( function (value) { JSON.parse(value) // boolean false }) // Or if you prefer using the await syntax JSON.parse(await AsyncStorage.getItem('someBoolean')) // boolean false
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.
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