Skip to content

Instantly share code, notes, and snippets.

@onosendi
Created February 27, 2022 20:32
Show Gist options
  • Save onosendi/6337c4bd46e78e2f7822553151d20771 to your computer and use it in GitHub Desktop.
Save onosendi/6337c4bd46e78e2f7822553151d20771 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));
};
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