Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Saving Data In Your React Native Mobile Application

TwitterFacebookRedditLinkedInHacker News

So you’ve been fiddling with React Native for a bit now like I have. If you’re like me then you’re at a point where you’re ready to look at saving and loading data in your mobile application.

Now I’ve previously demonstrated saving data with Ionic Framework, so the goals I’m about to share are going to be very similar. We’re going to focus on React Native’s AsyncStorage class to accomplish what we need.

A little disclaimer here. At the time of writing, React Native works pretty much only for iOS, so you’re going to need a Mac in order to proceed with what is in this article.

With that out of the way, go ahead and open your Terminal and execute the following command to start a new React Native project:

react-native init ReactProject

We won’t be using any external components in this tutorial, so as of now we’re ready to start coding.

Per the React Native documentation, the recommended way to persist data is through the AsyncStorage class. If you’re familiar with HTML5 local storage, then you’ll recognize that the two are very similar in how they function.

AsyncStorage uses key-value pairs so to save data you might do something like this:

AsyncStorage.setItem("myKey", "My value here");

If you want to obtain the data that you’ve saved, you can do a lookup based on the key value. It is an asynchronous operation that looks like the following:

AsyncStorage.getItem("myKey").then((value) => {
    this.setState({"myKey": value});
}).done();

The getItem method returns a promise because it is of course asynchronous.

With all this in mind, open your project’s index.ios.js file and include the following code:

"use strict";

var React = require("react-native");

var {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TextInput,
    AsyncStorage,
} = React;

var ReactProject = React.createClass({

    componentDidMount: function() {
        AsyncStorage.getItem("myKey").then((value) => {
            this.setState({"myKey": value});
        }).done();
    },

    getInitialState: function() {
        return { };
    },

    render: function() {
        return (
            <View style={styles.container}>
                <Text style={styles.saved}>
                    {this.state.myKey}
                </Text>
                <View>
                    <TextInput
                        style={styles.formInput}
                        onChangeText={(text) => this.saveData(text)}
                        value="" />
                </View>
                <Text style={styles.instructions}>
                    Type something into the text box. It will be saved to
                    device storage. Next time you open the application, the saved data
                    will still exist.
                </Text>
            </View>
        );
    },

    saveData: function(value) {
        AsyncStorage.setItem("myKey", value);
        this.setState({"myKey": value});
    }

});

var styles = StyleSheet.create({
    container: {
        padding: 30,
        flex: 1,
        justifyContent: "center",
        alignItems: "stretch",
        backgroundColor: "#F5FCFF",
    },
    formInput: {
        flex: 1,
        height: 26,
        fontSize: 13,
        borderWidth: 1,
        borderColor: "#555555",
    },
    saved: {
        fontSize: 20,
        textAlign: "center",
        margin: 10,
    },
    instructions: {
        textAlign: "center",
        color: "#333333",
        marginBottom: 5,
        marginTop: 5,
    },
});

AppRegistry.registerComponent('ReactProject', () => ReactProject);

Let’s break down what the above code is doing.

componentDidMount: function() {
    AsyncStorage.getItem("myKey").then((value) => {
        this.setState({"myKey": value});
    }).done();
}

When the application loads, the componentDidMount function will be called. We are going to load whatever data was saved and set the state when it is complete.

<Text style={styles.saved}>
    {this.state.myKey}
</Text>
<View>
    <TextInput
        style={styles.formInput}
        onChangeText={(text) => this.saveData(text)}
        value="" />
</View>

The above rendered items are for displaying what was saved and for saving new user inputted data. When the user enters text, the saveData function is called saving everything the user gives us.

Finally we have the saveData function:

saveData: function(value) {
    AsyncStorage.setItem("myKey", value);
    this.setState({"myKey": value});
}

The above function will save the input to storage and then immediately set the state so it can be displayed on the screen. I won’t go over the styling code that was included because it doesn’t advance the purpose of this article.

Go ahead and try it out. Save some data, quit the application, then re-open it. Is your data still there?

Conclusion

Although you could use HTML5 local storage, Facebook has created a more optimized method of storing data in React Native through the AsyncStorage class.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.