简体   繁体   中英

array.findIndex is not a function

While building cart in react native, when the cart is empty, I can add items in cart, but if I leave the screen and then comes back again to add more item or increase quantity of existing items in cart, I get an error "cartItems.findIndex is not a function"

Here is the code

const [cartItems, setCartItems] = useState([]);

const setCart = async value => {
  if (AsyncStorage) {
    await AsyncStorage.setItem("cart", JSON.stringify(value));
  }
};

const getCart = async () => {
  if (AsyncStorage && await AsyncStorage.getItem("cart")) {
    return await AsyncStorage.getItem("cart");
  }
  return [];
};


  // Get cart items on component mount
  useEffect(() => {
    getCart()
      .then(data => setCartItems(data))
      .catch(e => console.log(e));
  }, []);

  console.log(cartItems);

  // Add to cart
  const addToCart = product => {
    const index = cartItems.findIndex(item => item._id == product._id);
    // if item is not already in cart
    if (index === -1) {
      cartItems.push({
        ...product,
        quantity: 1
      });
      const updateCart = [...cartItems];
      setCartItems(updateCart);
      setCart(updateCart);
    } else {
      // if item already in cart
      cartItems[index].quantity += 1;
      const updateCart = [...cartItems];
      setCartItems(updateCart);
      setCart(updateCart);
    }
  };

and here is the data I get when i console.log(cartItems)

[{
"_id":"5e6aacca73fa9c323d666462",
"name":"Black T-shirt",
"description":"Grade A fabric. Awesome black t-shirt",
"price":10.99,
"image":{
"url":"/uploads/069963b003e5457ebee681a6537dbedc.png",
"__typename":"UploadFile"
},
"__typename":"Product",
"quantity":1
}]

您应该将字符串解析为 json 对象

cartItems  = JSON.parse(cartItems);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM