Sameer Yadav
Sameer Yadav

Reputation: 39

I want to change the state value of array while using Redux toolkit

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

Answers (2)

Asad Haroon
Asad Haroon

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

GʀᴜᴍᴘʏCᴀᴛ
GʀᴜᴍᴘʏCᴀᴛ

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

Related Questions