DEV Community

Discussion on: Persisting your React state in 9 lines

Collapse
 
jcaguirre89 profile image
Cristobal Aguirre • Edited

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:

const initialState = {
  //other state
  cartItems: JSON.parse(localStorage.getItem('cart_items')) || [],
}

function reducer(state, action) {
  switch (action.type) {
    case 'UPDATE_CART': {
      const { variantId, quantity } = action.payload;
      const updatedCartItems = state.cartItems.filter(
        i => i.variantId !== variantId
      );
      const cartItems = [...updatedCartItems, { variantId, quantity }];
      // write to localStorage <-- key part
      if (typeof window !== '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!