How to add the product to cart using ecommerce js?

Viewed 10
import React, { useState, useEffect } from 'react'

import {commerce} from './lib/commerce.js'
import {Products,Navbar} from './Components'

const App = () => {

  const [products, setProducts] = useState([]);
  const [cart, setCart] = useState({});




  const fetchProducts = async () => {
    const { data } = await commerce.products.list();

    setProducts(data);
  };

  const fetchCart = async () => {
    setCart(await commerce.cart.retrieve());
  };

  const handleAddToCart = async (productId, quantity) => {
    const item = await commerce.cart.add(productId, quantity);

    setCart(item.cart);
  };
      
    
      useEffect(()=>{
        fetchProducts();
        fetchCart();
      },[])
      
  return (
    <div>
        <Navbar totalItems = {cart.total_unique_items} />
        <Products products={products} onAddToCart={handleAddToCart}/>
    </div>
  )
}

export default App

This is the code that I have written for fetching the product from eCommercejs store but when I'm trying to add the product to the cart I'm getting an error as

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'total_unique_items')

Before clicking on the add to cart icon it's working properly. The total_unique_items property was readable but as soon as I clicked on add to cart button it became unreadable. Someone, please help me out.

0 Answers
Related