es6 concat not working properly with stringify (javascript)

Viewed 57

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 Answers

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]))
Related