cart
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import Cookies from "js-cookie";
const initialState = {
loading: true,
cartItems: [],
};
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
addToCart: (state: any, action: PayloadAction) => {
const actionItem: any = action.payload;
const existItem = state.cartItems.find(
(val: any) => val._id === actionItem._id
);
if (existItem) {
state.cartItems = state.cartItems.map((val: any) =>
val._id === existItem._id ? actionItem : val
);
} else {
state.cartItems = [...state.cartItems, actionItem];
}
Cookies.set("cart", JSON.stringify(state));
},
removeToCart: (state: any, action: PayloadAction) => {
const actionItem: any = action.payload;
state.cartItems = state.cartItems.filter(
(val: any) => val._id !== actionItem._id
);
},
},
});
export const { addToCart, removeToCart } = cartSlice.actions;
export default cartSlice.reducer;
Enter fullscreen mode
Exit fullscreen mode
store provider
"use client";
import { Provider } from "react-redux";
import { store } from "./store";
export function StoreProvider({ children }) {
return <Provider store={store}>{children}</Provider>;
}
Enter fullscreen mode
Exit fullscreen mode
Top comments (0)