React Native - Update AsyncStorage item nested key value?

Wonka picture Wonka · Sep 14, 2016 · Viewed 9.1k times · Source

I have a user stored via AsyncStorage like this:

// data has a few key/value pairs for the user object
AsyncStorage.setItem('user', JSON.stringify(data));

One of the key/value pairs in data is question_count with a value of 10

When the user deletes a question, how can I decrement the question_count value by 1 in AsyncStorage so the value is 9?

Here is what I tried:

AsyncStorage.getItem('user').then(data => {
    data.question_count--;
});

But that doesn't change the value. Any idea how to accomplish this?

Answer

RRikesh picture RRikesh · Sep 14, 2016

You should save the value again after decrementing it.

AsyncStorage.getItem( 'user' )
    .then( data => {

      // the string value read from AsyncStorage has been assigned to data
      console.log( data );

      // transform it back to an object
      data = JSON.parse( data );
      console.log( data );

      // Decrement
      data.question_count--;
      console.log( data );

      //save the value to AsyncStorage again
      AsyncStorage.setItem( 'user', JSON.stringify( data ) );

    }).done();