Home > Blockchain >  Add an object to an array using redux toolkit
Add an object to an array using redux toolkit

Time:08-12

everyone. I want to store an Object into an array using redux toolkit. Unfortunately, it is the case that a new object is not added, but simply replaced. How can I change this behavior ?

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
 warenkorb: [],
 preis: 0,
 bewertung: 0,
};

export const produktSlice = createSlice({
name: "produkt",
initialState,

reducers: {
hinzufügen: (state, action) => {

  // Also not work
  // state.warenkorb.push(action.payload);
  //

  state.warenkorb.push([...state.warenkorb, action.payload]);
  state.preis  = action.payload.preis * action.payload.anzahl;
},
entfernen: (state, action) => {
  if (state.warenkorb.includes(action.payload)) {
    state.warenkorb.splice(
      state.warenkorb.findIndex((id) => id === action.payload),
      1
    );
  }
},
bewerten: (state, action) => {
  state.bewertung = action.payload.bewertung;
 },
 },
});

export const { hinzufügen, entfernen, bewerten } = produktSlice.actions;

export default produktSlice.reducer;

As you can see, a new call is started each time with the new object enter image description here

And if I look at it with the help of the debugger, I get to see this. Why the first two objects and why do they look like this? enter image description here

CodePudding user response:

You should not push into the state you should replace the current state with a whole new state to ensure state updates

The code should be:


hinzufügen: (state, action) => {

  state.warenkorb = [...state.warenkorb, action.payload];
  
}

I made this sandbox for the total working example

  • Related