简体   繁体   中英

How to push multiple items into an array and load into async storage in react native?

I am attempting to push data into local storage in react native, in this case push multiple elements. I am attempting to use documentation pointed out here:

How do I set multiple values within Asyncstorage

How would I go about doing this properly? Below is some code:

What I am currently doing

const STORAGE_KEY = '@save_enableauto';
const DBLTIME_KEY = '@save_dbltime';

    state={
        times: Times,
        messageTimes: {
            dblTime: '12:00 pm',
            genTime: '12:00 pm'
        }
        enableAuto:false
    }


    //retrieves automatic messaging status
    _retrieveData = async () => {
        try {

          //pull data from local storage
          const enableAuto = await AsyncStorage.getItem(STORAGE_KEY);
          const dblTime = await AsyncStorage.getItem(DBLTIME_KEY);

          console.log('auto messages set: ',enableAuto);
          console.log('time data is:', dblTime);

          //reset state for time if it exists in local storage
          if(dblTime !==null) {
            this.setState(prevState => ({
                messageTimes: {                   // object that we want to update
                    ...prevState.messageTimes,    // keep all other key-value pairs
                    dblTime: dblTime       // update the value of specific key
                }
            }))
          } 

          //reset state for notifications if exists in local storage 
          if (enableAuto !== null) {
            // We have data!!
            console.log('receiving from local storage: ',enableAuto);
            this.setState({ enableAuto:eval(enableAuto) });
          }
        } catch (error) {
            alert('failed to load previous settings.')
          // Error retrieving data
        }
    };

//trying to set it up with one call
    _retrieveDataGroup = async () => {

        const items = JSON.stringify([['k1', STORAGE_KEY], ['k2', DBLTIME_KEY]]);

        try {
            const localData = AsyncStorage.multiGet(items, () => {
                //to do something
            });

            console.log('Group fetch: ',localData);

        } catch (error) {
            alert('failed to load previous settings.')
          // Error retrieving data
        }
    };   

right now what I receive when console logging group fetching is a promise:

Group fetch:  Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}

multiGet is a Promise. Add await before calling it.

const localData = await AsyncStorage.multiGet(items, () => {
  //to do something
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM