Finding error in get context state in Next.js.
This is adding part of the code of top
import "../styles/globals.css";
import { StoreProvider } from "../utils/store";
function MyApp({ Component, pageProps }) {
return (
<StoreProvider>
<Component {...pageProps} />
</StoreProvider>
);
}
export default MyApp;
Creating the context for cart operation (code)
import { createContext, useReducer } from "react";
export const ContextforCart = createContext();
const initialState = {
cart: { cartItems: [] },
};
function reducer(state, action) {
switch (action.type) {
case "CART_ADD_ITEM": {
const newItem = action.payload;
const existItem = state.cart.cartItems.find(
(item) => item.slug === newItem.slug
);
const cartItems = existItem
? state.cart.cartItems.map((item) =>
item.name === existItem.name ? newItem : item
)
: [...state.cart.cartItems, newItem];
return { ...state, cart: { ...state.cart, cartItems } };
}
default:
return state;
}
}
export function StoreProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
const value = { state, dispatch };
return (
<ContextforCart.Provider value={value}>
{children}
</ContextforCart.Provider>
);
}