2

I'd like to push new items to the cart array but the results I got are really unexpected, this approach works well with setState

await AsyncStorage.setItem('cart', JSON.stringify([...value, data]))

this in case there's some values stored on cart key otherwise I use

await AsyncStorage.setItem('cart', JSON.stringify([data]))

here's what I got as results

value : [522]
value : ["[","5","2","2","]",523]
value : ["[","\"","[","\"",",","\"","5","\"",",","\"","2","\"",",","\"","2","\"",",","\"","]","\"",",","5","2","3","]",524]

The ids I am pushing are strings like 123, 567, 789

  storeProduct = async (data) => {
    try {
      const value = await AsyncStorage.getItem('cart')
      if (value !== null) {
        await AsyncStorage.setItem('cart', JSON.stringify([...value, data]))
        console.log('value :', value)
      } else {
        await AsyncStorage.setItem('cart', JSON.stringify([data]))
      }
      this.alertCart()
    } catch (error) {
      this.setState({ error: error })
      console.log(error.message)
    }
  }

1 Answer 1

1

the type of value a string, you need to parse it first to be able to use the spread operator on it, otherwise it will be treated as a string which can be treated as an array of chars.

try this

await AsyncStorage.setItem('cart', JSON.stringify([...JSON.parse(value), data]))
Sign up to request clarification or add additional context in comments.

Comments

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.