Reputation: 39
I know this code is wrong, how to correct it. I am new to Web Dev. Please help !
import { createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
name: "cart",
initialState: {value: {list: []}},
reducers: {
addToCart: (state, action) => {
state.value = action.payload;
}
}
})
export default cartSlice.reducer;
Upvotes: 0
Views: 2787
Reputation: 492
Your approach is not good to addinCart.
import { createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
name: "cart",
initialState: {cart:[]},
reducers: {
addToCart: (state, action) => {
let index=state.cart.findIndex(e=>e.id===action.payload.id); // id should be unique.
if(index!=-1){
state.cart[index].qty++;
}
else {
let item={...action.payload,qty:1};
state.cart.push(item);
}
}
})
export default cartSlice.reducer;
Follow this approach for cart and similarly create removeFromCart reducer too.
Upvotes: 1
Reputation: 8918
At glance looking at your code it might be not returning state
at glance, try:
addToCart: (state, action) => state.value = action.payload
Upvotes: 0