Skip to content

Instantly share code, notes, and snippets.

@Reston
Created July 15, 2020 14:25
Show Gist options
  • Save Reston/9213806c14a9bd0cf9f9c53286d3e012 to your computer and use it in GitHub Desktop.
Save Reston/9213806c14a9bd0cf9f9c53286d3e012 to your computer and use it in GitHub Desktop.
Structure for useReducer with persist data
// forked from Cristobal Aguirre at https://dev.to/selbekk/persisting-your-react-state-in-9-lines-of-code-9go
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,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment