import React from 'react';
interface CartInterface {
items:
| {
id?: number;
title?: string;
price: number;
amount: number;
}[]
| null;
totalAmount: number;
totalPrice: number;
addItem: (item: any) => void;
removeItem: (id: number) => void;
}
const CartContext = React.createContext<CartInterface>({
items: null,
totalAmount: 0,
totalPrice: 0,
addItem: (item: any) => {},
removeItem: (id: number) => {},
});
export default CartContext;
let totalAmount = 0;
let totalPrice = 0;
let cartItems: {
id: number;
title: string;
price: number;
amount: number;
}[] = [];
export function CartProvider(props: any) {
function saveToLocalStorage(value: any) {
console.log(value);
localStorage.setItem('cart', value);
}
function addItemToCartHandler(item: {
id: number;
title: string;
price: number;
amount: number;
}) {
cartItems.push(item);
console.log(item);
saveToLocalStorage(cartItems);
}
function removeItemFromCartHandler(id: number) {
const cart = localStorage.getItem('cart');
console.log(cart);
}
const contextValue = {
items: cartItems,
totalPrice,
totalAmount,
addItem: addItemToCartHandler,
removeItem: removeItemFromCartHandler,
};
return (
<CartContext.Provider value={contextValue}>
{props.children}
</CartContext.Provider>
);
}