7

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?

1 Answer 1

25

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I needed. Thank you!
what about if there is a huge data, on that time I think this might take more time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.