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

Viewed 1000

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.

1 Answers

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

Related