Skip to content

Commit

Permalink
First iteration of the shopContext. have not implemented it to the ba…
Browse files Browse the repository at this point in the history
…sket yet.
  • Loading branch information
EsbenSE committed Apr 18, 2024
1 parent e5186b1 commit 7e8f9af
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions src/contexts/shopContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import React, { useState, useEffect } from "react";

Check failure on line 1 in src/contexts/shopContext.tsx

View workflow job for this annotation

GitHub Actions / build

'totalPrice' is declared but its value is never read.

Check failure on line 1 in src/contexts/shopContext.tsx

View workflow job for this annotation

GitHub Actions / build

'removeFromBasket' is declared but its value is never read.
import { Product, fetchProducts } from '../components/basket/product';


//type of state

interface ShopState {
products: Product[];
basketItems: Product[];
handleRemoveItem: (id: number) => void;
updateTotalPrice: (productID: number, price: number) => void;
addToBasket: (productID: number) => void;

}
//inital state
const initialState: ShopState = {
products: [],
basketItems: [],
handleRemoveItem: () => {},
updateTotalPrice: () => {},
addToBasket: () => {},
};

const ShopContext = React.createContext<ShopState>(initialState);


//Dispacth context


//ShopContextProvider.
type MyProviderProps = React.PropsWithChildren<{state?:ShopState }>

export function ShopContextProvider({children}:MyProviderProps) {
const [products, setProducts] = useState<Product[]>([]);
const [basketItems, setBasketItems] = useState<Product[]>([]);
const [totalPrice, setTotalPrice] = useState(0);
const [prices, setPrices] = useState(new Map<number, number>());


useEffect(() => {
fetchProducts().then((products) => {
setProducts(products);
});
}, []);

const updateTotalPrice = (productID: number, price: number) => {
//would like this to not be stateful
setPrices(prices.set(productID, price));
var tempTotalPrice = 0;
Array.from(prices.values()).forEach((price) => {
tempTotalPrice += price;
});
setTotalPrice((tempTotalPrice));
};



const handleRemoveItem = (id: number) => {
setBasketItems((prevItems) => prevItems.filter((item) => item.id !== id));
updateTotalPrice(id, 0);
};

const addToBasket = (productID: number) => {
setBasketItems((prev)=> ({...prev, [productID]:prev[productID+1]}) );
}


const removeFromBasket =(productID:number) => {
setBasketItems((prev)=> ({...prev, [productID]:prev[productID-1]}) );

}


return (
<ShopContext.Provider value = {{products,basketItems,handleRemoveItem,updateTotalPrice,addToBasket}}>
{children}
</ShopContext.Provider>



)
}

0 comments on commit 7e8f9af

Please sign in to comment.