How to Save Data with Asyncstorage

Asked

Viewed 6,131 times

6

I’m trying to save the mobile data without using a database. I found the AsyncStorage but I’m not able to implement.

saveData(){        
        let usuario = 'Usuario Top';
        AsyncStorage.setItem('usuario', usuario);
        Alert.alert(usuario);
    }

    displayData = async () => {
        try{
            let usuario = await AsyncStorage.getItem('usuario');
            alert(usuario);
        }catch(error){
            alert(error);
        }                   
    }

And I call for a button using

 onPress={() => this.saveData()}>

However the method is not called, rather, the try/catch is not read; My code has something wrong or the call of this type of method is not executed in this way?

OBS: made the Asyncstorage/ Imports version link of the tutorials I followed:

https://facebook.github.io/react-native/docs/asyncstorage.html

https://www.youtube.com/watch?v=aCe0h50hyCc

  • Your code is apparently correct. I created a executable snippet that you can see Asyncstorage in action. When you press Tap to Play you must click the Save button so it will save "User ${timestamp}" and when you click the Display button it will read from Asyncstorage the value that was saved and save in the state of the component.

3 answers

4

For small solutions I like to use the lib React-Native-simple-store

Or you can create a file, as an example my storage.js, and import the index.js of own simple-store

import { AsyncStorage } from 'react-native';

const store = {
    /**
     * Get a one or more value for a key or array of keys from AsyncStorage
     * @param {String|Array} key A key or array of keys
     * @return {Promise}
     */
    get(key) {
        if(!Array.isArray(key)) {
            return AsyncStorage.getItem(key).then(value => {
                return JSON.parse(value);
            });
        } else {
            return AsyncStorage.multiGet(key).then(values => {
                return values.map(value => {
                    return JSON.parse(value[1]);
                });
            });
        }
    },

    /**
     * Save a key value pair or a series of key value pairs to AsyncStorage.
     * @param  {String|Array} key The key or an array of key/value pairs
     * @param  {Any} value The value to save
     * @return {Promise}
     */
    save(key, value) {
        if(!Array.isArray(key)) {
            return AsyncStorage.setItem(key, JSON.stringify(value));
        } else {
            var pairs = key.map(function(pair) {
                return [pair[0], JSON.stringify(pair[1])];
            });
            return AsyncStorage.multiSet(pairs);
        }
    },

    /**
     * Updates the value in the store for a given key in AsyncStorage. If the value is a string it will be replaced. If the value is an object it will be deep merged.
     * @param  {String} key The key
     * @param  {Value} value The value to update with
     * @return {Promise}
     */
    update(key, value) {
        return deviceStorage.get(key).then(item => {
            value = typeof value === 'string' ? value : merge({}, item, value);
            return AsyncStorage.setItem(key, JSON.stringify(value));
        });
    },

    /**
     * Delete the value for a given key in AsyncStorage.
     * @param  {String|Array} key The key or an array of keys to be deleted
     * @return {Promise}
     */
    delete(key) {
        if (Array.isArray(key)) {
            return AsyncStorage.multiRemove(key);
        } else {
            return AsyncStorage.removeItem(key);
        }
    },

    /**
     * Get all keys in AsyncStorage.
     * @return {Promise} A promise which when it resolves gets passed the saved keys in AsyncStorage.
     */
    keys() {
        return AsyncStorage.getAllKeys();
    },

    /**
     * Push a value onto an array stored in AsyncStorage by key or create a new array in AsyncStorage for a key if it's not yet defined.
     * @param {String} key They key
     * @param {Any} value The value to push onto the array
     * @return {Promise}
     */
    push(key, value) {
        return deviceStorage.get(key).then((currentValue) => {
            if (currentValue === null) {
                // if there is no current value populate it with the new value
                return deviceStorage.save(key, [value]);
            }
            if (Array.isArray(currentValue)) {
                return deviceStorage.save(key, [...currentValue, value]);
            }
            throw new Error(`Existing value for key "${key}" must be of type null or Array, received ${typeof currentValue}.`);
        });
    },
};

export default store;

Ai just you import in your file, ex: import store from './services/storage';

And then manipulate the data with just the commands:

store.save(key, value);
store.update(key, value);
store.get(key);
store.push(key, value);
store.delete(key);

Passing key and value as parameters

In a basic example of an app of mine, I use the formik to receive data from a form, then save with the store.save() the object values with the key identification user

Then I present the data in the console searching with the store.get() for key user

export default withFormik({

  mapPropsToValues: () => ({ cpf: '', nome: '', telefone: '', celular: '', email: '' }),

  handleSubmit: (values) => {
    console.log(values);
    store.save('user', values)
    .then(console.log(store.get('user')));
  }

})(CadastroPessoaFisica);

Another lib I’ve been recommended as being good is React-Native-Storage but as the store so far has met my demands I have never tested.

But for a larger app I recommend using Redux.

1

Hello,

To be able to use async Storage it is necessary to use async/await, that one of the new concepts of ECMA-Script 6 to wait to complete an async action.

setAsyncStorage = async (valor) => {
  try {
    await AsyncStorage.setItem('chave', valor);
  } catch (e) {
    console.log(e.message);
  } 
}

Log in to React-Brasil: https://react-brasil.slack.com/

0

Your button when played will only perform the function saveData(), which saves data on AsyncStorage.

In order to read the data, you need some guy to call the displayData(). The Try/catch code will only be executed when you call the method displayData().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.