I’ve been following your NextJS Ecommerce Tutorial – Amazona
I’m getting an error on Layout.js
TypeError: Cannot destructure property ‘state’ of ‘(0 , react__WEBPACK_IMPORTED_MODULE_1__.useContext)(…)’ as it is undefined.

Then I updated the state and cart as follow:

const state = useContext(Store);
const cart = state;

Also updated the Link to Legacybehavior (see below code)
And I get this error:
TypeError: Cannot read properties of undefined (reading ‘cartItems’)
Line 26:

 {cart.cartItems.length > 0 && (
     |        ^

Full code below:

import React, { useContext } from ‘react’;
import Head from ‘next/head’;
import Link from ‘next/link’;
import { Store } from ‘../utils/store’;
export default function Layout({ title, children }) {
  const state = useContext(Store);
  const cart = state;
  return (
        <title>{title ? title + ‘ – Amazona’ : ‘Amazona’}</title>
        <meta name=”description”content=”Ecommerce website”/>
        <link rel=”icon”href=”/favicon.ico”/>
      <div className=”flex min-h-screen flex-col justify-between”>
          <nav className=”flex h-12 items-center px-4 justify-between shadow-md”>
            <Link href=”/”className=”text-lg font-bold”>
              <Link href=”/cart”className=”p-2″legacyBehavior>
                {cart.cartItems.length > 0 && (
                  <span className=”ml-1 rounded-full bg-red-600 px-2 py-1 text-xs font-bold text-white”>
                    {cart.cartItems.reduce((a, c) =>a + c.quantity, 0)}
              <Link href=”/login”className=”p-2″>
        <main className=”container m-auto mt-4 px-4″>{children}</main>
        <footer className=”flex h-10 justify-center items-center shadow-inner”>
          <p>Copyright &copy; 2022 Amazona</p>

AG Asked question October 31, 2022