React Native AsyncStorage storing values other than strings

前端 未结 6 1584
花落未央
花落未央 2021-01-03 17:46

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\         


        
6条回答
  •  花落未央
    2021-01-03 18:21

    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.

提交回复
热议问题