How to store data locally in React Native that is not a string

JSON.stringify({}) can be used to convert your data structure to a string.

You'd then use JSON.parse() to convert the string back to the original data structure.

You could create a nice service for this to eliminate some boilerplate code throughout your app. I've used React Native's built-in AsyncStorage API as the "persistent" storage facility in the example below. Adapt it as you see fit.

Example using React Native

Using the JSON API to store an object in persistent storage, i.e. React Native's AyncStorage, and then retrieving that value, and outputting it in a Text element. Untested.

Storage.js file - Note, this example object API provides a subset wrapper around what ReactNative's AsyncStorage API provides, you could adapt it to allow setting multiple keys for example, rather than one at a time.

//./storage.js
const Storage = {

    getItem: async function (key) {
        let item = await AsyncStorage.getItem(key);
        //You'd want to error check for failed JSON parsing...
        return JSON.parse(item);
    },
    setItem: async function (key, value) {
        return await AsyncStorage.setItem(key, JSON.stringify(value));
    },
    removeItem: async function (key) {
        return await AsyncStorage.removeItem(key);
    }
};

React Native component

//Usage...
import React, {Component} from "react";
import { View, Text } from "react-native";
import Storage from "./storage";

class Foo extends Component {

    constructor (props) {

        super(props);

        this.state = {
            greeting: ""
        };
    } 

    async componentDidMount () {

        await Storage.setItem("someObj", {value: "bar", id: 1});

        let obj = await Storage.getItem("someObj");

        this.setState({
             greeting: obj.value // Will be "bar" 
        });

    }

    render () {

         return (
               <View>
                    <Text>{this.state.greeting}</Text>
               </View>
         );
    }
}

Original example:

As I originally answered this on mobile, I did originally use the HTML5 localStorage api as an example, it was quicker to type (and it was cold!), here it is just in-case someone lands on this for react, not react-native mistakenly.

var StorageService = function  () {};

StorageService.prototype.get = function (key) {
    return JSON.parse(window.localStorage.getItem(key));
};

StorageService.prototype.set = function (key, value) {
    return window.localStorage.setItem(key, JSON.stringify(value));
};

recently i write pleex, you can take look at it https://github.com/E-RROR/pleex. you can save data in pure json or creating schemas with typechecking feature and more. thanks