Skip to content

Instantly share code, notes, and snippets.

@onosendi
Created March 6, 2022 16:49
Show Gist options
  • Save onosendi/b32772b1d082e8f434f431a99c732177 to your computer and use it in GitHub Desktop.
Save onosendi/b32772b1d082e8f434f431a99c732177 to your computer and use it in GitHub Desktop.
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));
};
const reset = () => {
setCart([]);
};
useEffect(() => {
setTotal(cart.reduce((acc, obj) => acc + obj.price, 0));
}, [cart]);
const memoized = useMemo(() => ({
cart,
total,
add,
remove,
reset,
}), [cart, total]);
return (
<CartContext.Provider value={memoized}>
{children}
</CartContext.Provider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment