I am working on a react shopping e-commerce website and i am using useContext and useReducer to set my cart state but each time i add to cart and reload the page my cart clears and reinitialize
each time it sets the state on reload it reinitialise it and i need the data to persist
MY CART STATE
const CartState = ({ children }) => {
let items = [];
const initialState = {
showCart: false,
products: items,
cartItems: [],
};
const { q } = useQuery({
queryKey: ["products"],
queryFn: async () => {
const data = await getDocs(collection(db, "/products"));
data.docs.forEach((doc) => {
let key = doc.id;
let item = doc.data();
items.push({ key, item });
});
},
});
const [state, dispatch] = useReducer(CartReducer, initialState);
const addToCart = (item) => {
dispatch({ type: ADD_TO_CART, payload: item });
};
const showHideCart = () => {
dispatch({ type: SHOW_HIDE_CART });
};
const removeItem = (id) => {
dispatch({ type: REMOVE_ITEM, payload: id });
};
return (
<ShopContext.Provider
value={{
showCart: state.showCart,
products: state.products,
cartItem: state.cartItems,
addToCart,
showHideCart,
removeItem,
}}
>
{children}
</ShopContext.Provider>
);
};
MY USEREDUCER COMPONENT
import { SHOW_HIDE_CART, ADD_TO_CART, REMOVE_ITEM } from "../types";
const CartReducer = (state, action) => {
switch (action.type) {
case SHOW_HIDE_CART: {
return { ...state, showCart: !state.showCart };
}
case ADD_TO_CART: {
return { ...state, cartItems: [...state.cartItems, action.payload] };
}
case REMOVE_ITEM: {
return {
...state,
cartItems: state.cartItems.filter((item) => item.id !== action.payload),
};
}
default:
return state;
}
};
export default CartReducer;
import { SHOW_HIDE_CART, ADD_TO_CART, REMOVE_ITEM } from "../types";
into the CarState function?console.log(action.type)
to print the value of action.type?