Created
July 15, 2020 14:25
-
-
Save Reston/9213806c14a9bd0cf9f9c53286d3e012 to your computer and use it in GitHub Desktop.
Structure for useReducer with persist data
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
// 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