cart cookies workin'

This commit is contained in:
Victor Turgeon 2022-11-08 02:52:55 -05:00
parent 261e89865c
commit 378534508b

View File

@ -1,5 +1,6 @@
import { useEffect } from "react";
import { createContext, useState } from "react";
import Cookies from "universal-cookie";
export const CartContext = createContext({
items: [],
@ -15,14 +16,26 @@ export const CartContext = createContext({
export function CartProvider({ children }) {
const [cartProducts, setCartProducts] = useState([]);
const cookies = new Cookies();
useEffect(() => {
if (cartProducts.length == 0) {
if (cookies.get('cart') != null && cookies.get('cart').length != 0)
setCartProducts(cookies.get('cart'));
}
}, []);
useEffect(() => {
cookies.set('cart', cartProducts, { path: '/', SameSite: 'strict', secure: true, maxAge: 2592000 })
}, [cartProducts]);
function addToCart(product, qty) {
setCartProducts([...cartProducts, { ...product, quantity: parseFloat(qty), remaining: parseFloat(product.quantity) }]);
}
function getProductQuantity(id) {