Hi,
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 (
<>
<Head>
<title>{title ? title + ‘ – Amazona’ : ‘Amazona’}</title>
<meta name=”description”content=”Ecommerce website”/>
<link rel=”icon”href=”/favicon.ico”/>
</Head>
<div className=”flex min-h-screen flex-col justify-between”>
<header>
<nav className=”flex h-12 items-center px-4 justify-between shadow-md”>
<Link href=”/”className=”text-lg font-bold”>
amazona
</Link>
<div>
<Link href=”/cart”className=”p-2″legacyBehavior>
Cart
{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)}
</span>
)}
</Link>
<Link href=”/login”className=”p-2″>
Login
</Link>
</div>
</nav>
</header>
<main className=”container m-auto mt-4 px-4″>{children}</main>
<footer className=”flex h-10 justify-center items-center shadow-inner”>
<p>Copyright © 2022 Amazona</p>
</footer>
</div>
</>
);
}