7

I use @reduxjs/toolkit and my state contains: allSlides: ISlide[];

When I try to change anything in allSlides like ex.

setAllSlides(state, action: PayloadAction<ISlide[]>) {
  state.allSlides = action.payload;
},
storeNewSlide(state, action: PayloadAction<ISlide>) {
  state.allSlides.push(action.payload);
},

I get a TS error

Type 'ISlide' is not assignable to type 'WritableDraft<ISlide>'

I don't have problem with changing array of primitive values or just one property in objects, but I don't know how to change correctly whole array or specific object in array.

Żywy
  • 393
  • 2
  • 12

2 Answers2

1

You have to add the type in the action

ie:

export const storeNewSlide = createAsyncThunk(
  "slides/storeNewSlide",
  async (slide: ISlide) => {
    return {
      slide,
    };
  }
);

and then in your allSlides:

storeNewSlide(state, action: PayloadAction<ISlide>) {
  state.allSlides.push(action.payload.slide);
},

Same for the array of slides

1

Had similar issue, I think redux doesn't like direct mutation of state object.

so spread operator solved for me

setAllSlides(state, action: PayloadAction<ISlide[]>) {
  state = { ...state, allSlices:action.payload };
},
storeNewSlide(state, action: PayloadAction<ISlide>) {
  state = { ...state, allSlices: [...state.allSlices, action.payload } ];
},
yuki
  • 199
  • 1
  • 2
  • 11
  • 2
    This is likely true of redux, but not when using Redux Toolkit as it uses Immer internally. See https://redux-toolkit.js.org/usage/immer-reducers – Kristopher Jun 01 '23 at 14:47
  • Following @Kristopher's lead, I see this works for me: `Object.assign(state, { allSlices: action.payload });` – kennethc Aug 16 '23 at 04:33