I adapted both this post and this blog post by Swizec Teller to get what I wanted using useReducer. I'm making an ecommerce site and wanted to persist the cart items. So I did:
constinitialState={//other statecartItems:JSON.parse(localStorage.getItem('cart_items'))||[],}functionreducer(state,action){switch(action.type){case'UPDATE_CART':{const{variantId,quantity}=action.payload;constupdatedCartItems=state.cartItems.filter(i=>i.variantId!==variantId);constcartItems=[...updatedCartItems,{variantId,quantity}];// write to localStorage <-- key partif(typeofwindow!=='undefined'){localStorage.setItem('cart_items',JSON.stringify(cartItems));}return{...state,cartItems,};}
and then plugged that into context. If you need more context, I'm using gatsby and followed this guide to set up the state mgt. logic.
Hope it helps!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I adapted both this post and this blog post by Swizec Teller to get what I wanted using useReducer. I'm making an ecommerce site and wanted to persist the cart items. So I did:
and then plugged that into context. If you need more context, I'm using gatsby and followed this guide to set up the state mgt. logic.
Hope it helps!