Home > Mobile >  React Native Async Storage setItem call fails
React Native Async Storage setItem call fails

Time:10-01

I'm writing a simple Async Storage set Item call in React Native to store my store's cart data. But the call fails. I can't find possible reason why it so as there is no mention of such in the documentation. I have added the relevant code. Please help would be appreciated.

const ProductDetailScreen = (props) => {
  const {product} = props.route.params;

  const getCart = async () => {
    return await AsyncStorage.getItem('cart');
  };

  const cart = getCart();

  const addToCart = async () => {
    try {
      await AsyncStorage.setItem('cart', [
        ...cart, JSON.stringify(product),
      ]);
    } catch (e) {
      console.error(`Failed to add item: {${JSON.stringify(product)}} to cart`);
    }
  };

  return (
    <>
      <TouchableOpacity onPress={addToCart}>
          <Button>
            <Text style={styles.btnText}>Add to Cart</Text>
          </Button>
        </TouchableOpacity>
    </>
  )
};

export default ProductDetailScreen;

error log

ERROR  Failed to add item: {{"id":2,"name":"Scene Stealers","description":"Corset cuts","price":250,"image":5,"colors":["#0F140D","#DD8560","#E1E0DB"],"sizes":["S","M","L"]}} to cart

CodePudding user response:

You can only store/set string data in AsyncStorage while you are trying to store Array

enter image description here

await AsyncStorage.setItem('cart', JSON.stringify([...cart, JSON.stringify(product)]))
  • Related