0

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

3
  • You want to replace or just append ? Commented Aug 12, 2022 at 11:22
  • I want to append new objects Commented Aug 12, 2022 at 11:26
  • I assume in this entfernen reducer ? Commented Aug 12, 2022 at 11:31

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thx. But also didn't work
@Captai-N please check the sandbox example i added

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.