0

at my first attempt to incorporate Typescript into my redux toolkit , i got an issue defining my reducers in Redux Slice

import { createSlice } from "@reduxjs/toolkit";
import { data } from "../data/Reviews";

interface ReviewStateProps {
  index: number;
}

const initialState: ReviewStateProps = { index: 0 };

const reviewSlice = createSlice({
  name: "review",
  initialState,
  reducers: {
    nextPerson: (state) => {
      let newIndex = state.index + 1;
      if (newIndex > data.length - 1) {
        return 0;
      }
      if (newIndex < 0) {
        return data.length - 1;
      }
      return newIndex;
    },
    prevPerson: (state) => {
      let newIndex = state.index - 1;
      if (newIndex > data.length - 1) {
        return 0;
      }
      if (newIndex < 0) {
        return data.length - 1;
      }
      return newIndex;
    },
  },
});

export const reviewActions = reviewSlice.actions;

export default reviewSlice.reducer;

at my above code i get squiggly line under my reducers (nextPerson , prevPerson) with a message as follows

(property) nextPerson: (state: WritableDraft<ReviewStateProps>) => number
Type '(state: WritableDraft<ReviewStateProps>) => number' is not assignable to type 'CaseReducer<ReviewStateProps, { payload: any; type: string; }> | CaseReducerWithPrepare<ReviewStateProps, PayloadAction<any, string, any, any>>'.
  Type '(state: WritableDraft<ReviewStateProps>) => number' is not assignable to type 'CaseReducer<ReviewStateProps, { payload: any; type: string; }>'.
    Type 'number' is not assignable to type 'void | ReviewStateProps | WritableDraft<ReviewStateProps>'.ts(2322)

appreciate if someone can explain to me what is the issue and how i can solve it. thanks

Thecountofs
  • 25
  • 1
  • 5

1 Answers1

0

return newIndex; is incorrect, you have to return a full state with the same type as the initialState (ReviewStateProps).

    prevPerson: (state) => {
      state.index = state.index - 1;
      if (newIndex > data.length - 1) {
        state.index = 0;
      }
      if (newIndex < 0) {
        state.index = data.length - 1;
      }
      return state;
    },

The above code only works because Redux-Toolkit uses immersion behinds the scene.

Benoît P
  • 3,179
  • 13
  • 31