How do I set multiple values within Asyncstorage

Linu Sherin picture Linu Sherin · Oct 24, 2018 · Viewed 8.3k times · Source

How do I set multiple values within Asyncstorge?.Because I'm trying to set token and user_id .These are the server response values. This is how response looks like

json

{ error: 0,
  data: 'User registered Successfully',
  userData:
   { pwd: 'lmlmlm',
     phone_no: '9898989',
     user_name: '',
     status: 1,
     date: 2018-10-24T07:12:20.656Z },
  user_id: 60,
  token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' }

And in react native I've written like this after user registrtaion.

.then((response) => response.json())
            .then((responseData) =>
            {
                console.log(responseData);
                 AsyncStorage.setItem('id_token', responseData.token),
                 AsyncStorage.setItem('user_id', responseData.user_id),
                    Actions.firstScreen();

                    });

And in my home page I'm accessing the token and user_id within AsyncStorage as

 AsyncStorage.getItem('id_token').then((usertoken) =>{
                this.setState({'id_token' : usertoken});
                console.log(usertoken);
            })
            AsyncStorage.getItem('user_id').then((uid) => {
              this.setState({'user_id': uid});
              console.log(uid);
            })

But I'm getting only the token , consoled result of uid is getting as null.But when I consoled the responseData I've values within it.Please help me

Answer

nahoang picture nahoang · Oct 24, 2018

Please check this docs at link

So you can use like this:

const items = [['k1', 'val1'], ['k2', 'val2']]
AsyncStorage.multiSet(items, () => {
    //to do something
});

Cheer!