I cant for the life of me find where I found this pattern but I’m trying to implement it and having some issues.
When I use `cartState.addToCart()`, the console.log fires from inside the provider and also in all the components where I use `const cartState = useCartContext();`, however the state in the components is always the default state, while the state in the provider is the correct, updated state.
CartWithPopOver.tsx:
export default function CartWithPopover() { const cartState = useCartContext(); console.log(‘State from cartWithPopover’, cartState); … return ( <div>cartState.cartTotalItems</div> )
CartContext.tsx:
const DefaultCartState: CartState = { cartTotalCost: 0, cartTotalItems: 0, cartItems: [], addToCart: (item: ProductWithImages, quantity: number): void => { throw new Error(“Function not implemented.”); } } export const CartContext = createContext<CartState>(DefaultCartState); export const useCartContext = () => useContext(CartContext); export const CartContextProvider = (props:any) => { const [cartState, setCartState] = useState<CartState>(DefaultCartState); const cartProviderValue: CartState = { cartTotalCost: 0, cartTotalItems: 0, cartItems: [], addToCart: function (item: ProductWithImages, quantity: number): void { const newState2 = {…cartState} newState2.cartTotalItems++; setCartState(newState2); console.log(`setting cart state`, item, quantity, prevState); } return ( <CartContext.Provider value={cartProviderValue}>{props.children}</CartContext.Provider> ) }
submitted by /u/dangerzone2
[link] [comments]