Created
February 27, 2022 20:32
-
-
Save onosendi/6337c4bd46e78e2f7822553151d20771 to your computer and use it in GitHub Desktop.
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
import { | |
createContext, | |
useContext, | |
useEffect, | |
useMemo, | |
useState, | |
} from 'react'; | |
export const CartContext = createContext(null); | |
export function useCartContext() { | |
return useContext(CartContext); | |
} | |
export function CartProvider({ children }) { | |
const [cart, setCart] = useState([]); | |
const [total, setTotal] = useState(0); | |
const add = (name, price) => { | |
setCart(cart.concat([{ name, price }])); | |
}; | |
const remove = (name) => { | |
setCart(cart.filter((obj) => obj.name !== name)); | |
}; | |
useEffect(() => { | |
setTotal(cart.reduce((acc, obj) => acc + obj.price, 0)); | |
}, [cart]); | |
const foo = useMemo(() => ({ | |
cart, | |
total, | |
add, | |
remove, | |
}), [cart, total, add, remove]); | |
return ( | |
<CartContext.Provider value={foo}> | |
{children} | |
</CartContext.Provider> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment