Hi guys recently i am using reactjs to build add to cart function, because I don't have backend server to store customer cart so I store it at localstorage . When i click add to cart the item is being set into the localstorage , However after refreshing the page, cartItems value being set to default.
export const Store = createContext();
const initialState = {
cart: {
cartItems :[]
},
};
export function StoreProvider(props) {
const [items, setItems] = useLocalStorage('cartItems', []);
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
setItems(state.cart.cartItems);
}, [setItems,state.cart.cartItems]);
const value = { state, dispatch };
return (<Store.Provider value={value}>{props.children}</Store.Provider>);
}
function reducer(state, action) {
switch (action.type) {
case 'ADD_TO_CART': {
const newItem = action.payload;
const existItem = state.cart.cartItems.find(
(item) => item.id === newItem.id
);
const cartItems = existItem
? state.cart.cartItems.map((item) =>
item.id === existItem.id ? newItem : item
)
: [...state.cart.cartItems, newItem];
...
