Skip to content

Commit

Permalink
feat:storing added cartItems to local storage to fetch Back
Browse files Browse the repository at this point in the history
  • Loading branch information
anwesha authored and anwesha committed May 21, 2024
1 parent 9b300aa commit 63d24f9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/Context/ShopContext.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import React, { createContext, useState } from "react";
import all_product from "../Components/Assets/all_product";
import {useLocalStorage} from "../Hooks/uselocalstorage";

export const ShopContext = createContext(null);

const ShopContextProvider = (props) => {
const [cartItems, setcartItems] = useState([]);
const [cartItems, setcartItems] = useLocalStorage("shopping cart",[]);

const [theme,setTheme]=useState("dark");
const addToCart = (itemId, size, quantity) => {
const existingCartItemIndex = cartItems.findIndex(item => item.id === itemId && item.size === size);
Expand All @@ -19,27 +21,30 @@ const ShopContextProvider = (props) => {
}
return item;
});

setcartItems(updatedCartItems);
} else {
const cartProduct = all_product.find((product) => product.id === itemId);
cartProduct.size = size;
cartProduct.quantity = quantity;
setcartItems([...cartItems, cartProduct]);
}


};

const removeFromCart = (itemId) => {
setcartItems(cartItems.filter((product) => product.id !== itemId));
};

const getTotalCartAmount = () => {
return cartItems.reduce((total, product) => total + (product.new_price * product.quantity), 0);
return cartItems.reduce((total, product) => total + (product.new_price * product.quantity), 0);
};



const getTotalCartItems = () => {
return cartItems.length;
return cartItems.length
};

const contextValue = {
Expand Down
18 changes: 18 additions & 0 deletions src/Hooks/uselocalstorage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import {useEffect, useState} from "react";

export function useLocalStorage(key, initialValue ) {
const [value, setValue] = useState(() =>{
const jsonValue = localStorage.getItem(key)
if(jsonValue != null) return JSON.parse(jsonValue)

// if(typeof initialValue === "function") return initialValue()
return initialValue
})


useEffect(()=>{
localStorage.setItem(key, JSON.stringify(value))
}, [key, value])

return [value, setValue]
}

0 comments on commit 63d24f9

Please sign in to comment.