Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Update AsyncStorage item nested key value?

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?

like image 604
Wonka Avatar asked Sep 14 '16 04:09

Wonka


1 Answers

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();
like image 159
RRikesh Avatar answered Oct 21 '22 16:10

RRikesh