javascriptreactjse-commercecommercecommerce.js

Getting error when reloading the Commerce.js Checkout page (react tutorial)


I'm currently doing the React.js checkout tutorial for the Commerce.js Api.

When i click on the checkout button from the cart it takes me to the checkout page and does generate the checkout token as it should, but I've noticed that when i reload the checkout page the console shows the following errors: Image of errors.

And this is the code for the Checkout Page:

import React, { useEffect, useState } from 'react';
import { commerce } from '../../lib/commerce';
import './styles.css';

const Checkout = ({ cart }) => {

    const [checkoutToken, setCheckoutToken] = useState({});

    useEffect(() => {
        generateCheckoutToken();
    }, [])

    const generateCheckoutToken = () => {
        if (cart.line_items.length) {
            commerce.checkout.generateToken(cart.id, { type: 'cart' })
                .then((token) => {
                    setCheckoutToken(token);
                    console.log(checkoutToken);
                }).catch((error) => {
                    console.log('There was an error in generating a token', error);
                });
        }
    }

    return (
        <div>
            Checkout
        </div>
    )
}

export default Checkout

I think it has something to do with the cart not loading before the generateCheckoutToken() function gets used but i don't understand how to fix the problem.

Here is the App.js:

import { useEffect, useState } from 'react';
import { commerce } from './lib/commerce';
import { Routes, Route } from 'react-router-dom';
import ProductsList from './components/ProductList/ProductsList';
import Cart from './components/Cart/Cart';
import Checkout from './components/Checkout/Checkout';
import './App.css';

function App() {

  const [products, setProducts] = useState([]);
  const [cart, setCart] = useState({});
  const [prductLoading, setProductLoading] = useState(false);
  const [cartBtn, setCartBtn] = useState(false);

  const fetchProducts = () => {
    commerce.products.list().then((products) => {
      setProducts(products.data);
      setProductLoading(false);
    }).catch((error) => {
      console.log('There was an error fetching the products', error);
    });
  }

  const fetchCart = () => {
    commerce.cart.retrieve().then((cart) => {
      setCart(cart)
    }).catch((error) => {
      console.error('There was an error fetching the cart', error);
    });
  }

  const handleAddToCart = (productId, quantity) => {
    commerce.cart.add(productId, quantity).then((item) => {
      setCart(item.cart)
    }).catch((error) => {
      console.error('There was an error adding the item to the cart', error);
    });
  }

  const handleUpdateCartQty = (lineItemId, quantity) => {
    commerce.cart.update(lineItemId, { quantity }).then((resp) => {
      setCart(resp.cart)
    }).catch((error) => {
      console.log('There was an error updating the cart items', error);
    });
  }

  const handleRemoveFromCart = (lineItemId) => {
    commerce.cart.remove(lineItemId).then((resp) => {
      setCart(resp.cart)
    }).catch((error) => {
      console.error('There was an error removing the item from the cart', error);
    });
  }

  const handleEmptyCart = () => {
    commerce.cart.empty().then((resp) => {
      setCart(resp.cart)
    }).catch((error) => {
      console.error('There was an error emptying the cart', error);
    });
  }

  const handleCloseCart = () => {
    setCartBtn(false);
  }

  useEffect(() => {
    setProductLoading(true);
    fetchProducts();
    fetchCart();
  }, [])

  // console.log(cart);

  return (
    <div className="App">
      <Routes>
        <Route
          exact
          path='/'
          element={
            <div className='home'>
              <div className={`cart-button ${cartBtn && 'cartOpen'}`}>
                {cartBtn ?
                  <Cart
                    cart={cart}
                    onUpdateCartQty={handleUpdateCartQty}
                    onRemoveFromCart={handleRemoveFromCart}
                    onEmptyCart={handleEmptyCart}
                    closeCartBtn={handleCloseCart}
                  />
                  :
                  <p onClick={() => setCartBtn(true)}>Open cart</p>
                }
              </div>
              {prductLoading ?
                'Loading...'
                :
                <ProductsList
                  products={products}
                  onAddToCart={handleAddToCart}
                />
              }
            </div>
          }
        />
        <Route
          exact
          path='/checkout'
          element={
            <Checkout 
              cart={cart}
            />
          }
        />
      </Routes>
    </div>
  );
}

export default App;

I would appreciate it if someone could tell me what I'm missing, thanks for your help!!


Solution

  • Issue

    When you initialize cart in the App state, it is an empty object {}. That is passed down as a prop to Checkout.

    As soon as Checkout mounts, it calls generateCheckoutToken, which tries to read cart.line_items.length. If this happens before fetchCart is called in the parent, cart is an empty object with no line_items to count. It's a race condition.

    One solution

    One solution would be to listen for cart to change in the useEffect, and only call generateCheckoutToken when cart has line_items. This might not support your future design goals, but it should resolve this error.

    // Checkout
    useEffect(() => {
      if(cart.line_items) { 
        generateCheckoutToken();
      }
    }, [cart])