React Native AsyncStorage storing values other than strings
Asked Answered
Y

7

51

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..

You answered 24/2, 2016 at 7:48 Comment(0)
E
75

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
    }
})
Emulsion answered 24/2, 2016 at 8:12 Comment(3)
Yeah that's what it seemed like although I thought it should be better than that. Thanks.You
Yes, but take a look at third party libraries, some are really powerful and useful.Emulsion
How will i store boolean. I am getting a promise object in return, when I Stringify it.Mc
C
49

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.

Coplin answered 25/2, 2016 at 14:3 Comment(2)
If you do use the callback and not the promise approach, the signature of the callback is actually: function(err, value) => JSON.parse(value)Hast
@PatrickBassut you're right, my bad. I foolishly didn't confirm in their docs before writing my answer. Did edit it now though. Thanks for pointing it outCoplin
J
9

I have set value in "name" key in AsyncStorage

AsyncStorage.setItem("name", "Hello");

To get value from key "name"

AsyncStorage.getItem("name").then((value) => {
   console.log("Get Value >> ", value);
}).done();

Output will be as follows:

'Get Values >> ', 'Hello'
Justajustemilieu answered 20/9, 2016 at 10:58 Comment(0)
C
8

I always use/create a wrapper module around AsyncStorage, utilising JSON.parse & JSON.stringify on the data coming in and out.

This way you remove the need to call JSON.parse & JSON.stringify inside your business logic. This keeps the code a bit nicer on the eye.

Something like

import AsyncStorage from '@react-native-async-storage/async-storage';

export const Storage = {
    
    getItem: async (key) => {
        try {
             let result = await AsyncStorage.getItem(key);
             return JSON.parse(result);
        } 
        catch (e) {
             throw e;
        } 
    },

    setItem: async (key, value, callback) => {
        
        try {
            const item = JSON.stringify(value);

            return await AsyncStorage.setItem(key, item, callback);
        } catch (e) {
            throw e;
        }
    }
}

// usage

async function usage () {
    
    const isLeeCool = true;
    const someObject = { name: "Dave" };
    const someArray = ["Lee", "Is", "Cool."];

    try {
        // Note Async storage has a method where you can set multiple values,
        // that'd be a better bet here (adding it to the wrapper).
        await Storage.setItem("leeIsCool", leeIsCool);
        await Storage.setItem("someObject", someObject);
        await Storage.setItem("someArray", someArray);
    }  catch (e) {}

    // Some point later that day...

    try {

        console.log(await Storage.getItem("leeIsCool"));
        console.log(await Storage.getItem("someObject"));
        console.log(await Storage.getItem("someArray"));
    }  catch (e) {}
}
Colligan answered 21/1, 2020 at 14:49 Comment(0)
C
0
 await AsyncStorage.setItem('saveUserCredential', JSON.stringify(true/false), () => {
        console.log("saveUserCredential save details " +flag);
 });



  AsyncStorage.getItem('saveUserCredential').then(async (value) => {
               let userLogin = await JSON.parse(value);

               if(userLogin ){
                   this.props.navigation.navigate("HomeScreen");
               }else {
                  this.props.navigation.navigate("LoginScreen");
               }
           });
Cookhouse answered 3/1, 2020 at 7:43 Comment(0)
K
0

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.

import { XStorage } from 'react-native-easy-app';
import { AsyncStorage } from 'react-native';

export const RNStorage = {// RNStorage : custom data store object
     token: undefined, // string type
     isShow: undefined, // bool type
     userInfo: undefined, // object type
 };   

const initCallback = () => {

     // From now on, you can write or read the variables in RNStorage synchronously

     // equal to [console.log(await AsyncStorage.getItem('isShow'))]
     console.log(RNStorage.isShow); 

     // equal to [ await AsyncStorage.setItem('token',TOKEN1343DN23IDD3PJ2DBF3==') ]
     RNStorage.token = 'TOKEN1343DN23IDD3PJ2DBF3=='; 

     // equal to [ await AsyncStorage.setItem('userInfo',JSON.stringify({ name:'rufeng', age:30})) ]
     RNStorage.userInfo = {name: 'rufeng', age: 30}; 
};

XStorage.initStorage(RNStorage, AsyncStorage, initCallback); 
Koster answered 1/4, 2020 at 5:1 Comment(0)
P
0

pass a toString function to it...AsyncStorage requires that keys be strings, not numbers.

Here: await AsyncStorage.setItem(item.id.toString(), 'true');

Pentyl answered 27/3, 2023 at 7:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.