forked from infoshareacademy/jfdzr12-project-react
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
69d17bd
commit d5848d6
Showing
4 changed files
with
70 additions
and
43 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import React, { PropsWithChildren, createContext, useContext, useState } from 'react'; | ||
import { Product } from "./basketContext.types" | ||
|
||
interface BasketContextType { | ||
basket: Product[]; | ||
addToBasket: (product: Product) => void; | ||
removeFromBasket: (productId: number) => void; | ||
} | ||
|
||
const BasketContext = createContext<BasketContextType | undefined>(undefined); | ||
|
||
const BasketProvider: React.FC = ({ children }: PropsWithChildren) => { | ||
const [basket, setBasket] = useState<Product[]>([]); | ||
|
||
const addToBasket = (product: Product) => { | ||
setBasket([...basket, product]); | ||
} | ||
|
||
const removeFromBasket = (productId: number) => { | ||
setBasket(basket.filter(item => item.id !== productId)); | ||
} | ||
|
||
return ( | ||
<BasketContext.Provider value={{ basket, addToBasket, removeFromBasket }}> | ||
{children} | ||
</BasketContext.Provider> | ||
); | ||
} | ||
|
||
const useBasket = () => { | ||
const context = useContext(BasketContext); | ||
if (!context) { | ||
throw new Error('useBasket must be used within a BasketProvider'); | ||
} | ||
return context; | ||
} | ||
|
||
export { BasketProvider, useBasket }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
export interface Product { | ||
author: string; | ||
height: number; | ||
id: number; | ||
price: number; | ||
url: string; | ||
width: number; | ||
} |
This file was deleted.
Oops, something went wrong.