• Home
  • React Native
  • React Native persist data. Saving and reading data from AsyncStorage

React Native persist data. Saving and reading data from AsyncStorage


In previous post: React Native editable list I showed, how to edit data of single element on list. The edited data was saved to the component state, which allowed it to be displayed on the screen. However, when you close the application, the data resets and are not saved. How to change that? AsyncStorage will help.

React native AsyncStorage example.

AsyncStorage to miejsce w aplikacji, które przechowuje dane i do którego możemy się w każdej chwili odwołać. Działa asynchronicznie, a dane w nim przechowywane są globalne. Od stanu komponentu różni się między innymi tym, że pamięta dane nawet po zamknięciu aplikacji.

AsyncStorage is a place in the application that stores data. We can refer to it at any time. It works asynchronously and the data stored in it are global. In contrast to component state, it remembers data even after closing the application.

Before we use AsyncStorage, we must import component:

import {..., AsyncStorage } from 'react-native';

Function setDataToAsyncStore sets data in AsyncStorage in string, and function getDataFromAsyncStore reads the data. If data no exists, then in memory are written default data. Each time after reading the data (and changing their state from string to the original form), the getDataFromAsyncStore function saves their state in the component state, from where they are read and rendered by the component.


Persist data in React Native – set data to AsyncStorage

setDataToAsyncStore = async () => {
        try {
            let data = this.state.data;
            await AsyncStorage.setItem('data', JSON.stringify(data));        
        } catch (error) {
            console.log('AsyncStorage set data error in List component', error.message)
        }
    } 

Fetch data in React Native – get data from AsyncStorage

getDataFromAsyncStore = async () => {
        try {
            let data = await AsyncStorage.getItem('data');
            if (data === null) {
                data = this.initData
                // saving data as string
                await AsyncStorage.setItem('data', JSON.stringify(data)                 );
                this.setState({ data: data })
                return
            }
            data = JSON.parse(data);
            this.setState({ data: data })
        } catch (error) {
            console.log('AsyncStorage get data error in List component', error.message)
        }
     }

The getDataFromAsyncStore function can be called e.g. in the constructor or in the componentDidMount() method, so that each time the application is started, the data from the AsyncStorage memory is saved to the component state.

 
export default class MyClass extends Component {
constructor(props) {
super(props);

  this.initData = [
  {id: 1, text: 'Some Text 1'},
  {id: 2, text: 'Some Text 2'},
  {id: 3, text: 'Some Text 3'},
  ]
this.state = {
data: this.initData,
};
this.getDataFromAsyncStore();
}
...
}

or

componentDidMount() {
   this.getDataFromAsyncStore();
}

AsyncStorage multiSet example

What about if we want to read or write bulk data to AsyncStorage? The multiGet, mutliSet and getAllKeys methods will be used for this.

If we want to save several keys and their corresponding values, we will use the following notation:

keys = [['test1', 'value for test1 key'], ['test2', 'value for test2 key']]
AsyncStorage.multiSet(keys, () => {
   console.log('Saved data with multiset method')
} );   

AsyncStorage multiGet example

In case we want to download all the keys that are stored in AsyncStorage, just type:

AsyncStorage.getAllKeys() // getting All Keys

However, to download specific keys and their values, we will use the following notation:

let keys = ['test1', 'test2'];
AsyncStorage.multiGet(keys, (err, stores) => {
    stores.map((result, i, store) => {
    // get at each store's key/value so you can work with it
    let key = store[i][0];          // shows key
    let value = store[i][1];        // shows value
    let multiget = result;          // shows key and value
    // Do something with result
    });
});

In the above case, we get the key (let key), the value itself (let value), or the key-value pair (let multiget) and we can use them, e.g. to save them in the component state.


AsyncStorage multiRemove example

And how to delete multiple keys and their values?

let keys = ['test1', 'test2'];
AsyncStorage.multiRemove(keys, (err) => {
  // keys test1 & test2 removed, if they existed
  // do most stuff after removal (if you want)
     console.log('all keys removed');
});

More about AsyncStorage you can find in documentation.

Joanna

Leave a Reply

Your email address will not be published. Required fields are marked *