Created
March 6, 2022 16:49
-
-
Save onosendi/b32772b1d082e8f434f431a99c732177 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)); | |
}; | |
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