Home > OS >  How to type 'prepare' function in redux-toolkit
How to type 'prepare' function in redux-toolkit

Time:06-03

I am using redux-toolkit prepare function to construct the final payload value.

    addTodo: {
      reducer: (state, action) => {
        state.push(action.payload);
      },
      // ERROR: **Type '{ payload: Todo; }' is missing the following properties from type 'Omit<PayloadAction<any, string, any, any>, "type">': meta, errorts**
      prepare: (todoMessage: string): { payload: Todo } => {
        return {
          payload: { message: todoMessage, id: uuid(), completed: false }
        };
      }
    },

How can I type prepare function to remove the typescript error?

Check the error here.

CodePudding user response:

    addTodo: {
      reducer: (state, action: PayloadAction<Todo>) => {
        state.push(action.payload);
      },
      prepare: (todoMessage: string) => {
        return {
          payload: { message: todoMessage, id: uuid(), completed: false }
        };
      }
    },

you just need to add a payload type on the action.

CodePudding user response:

type DefaultPayload = any;`

Define whole state in your reducer

type WholeState = {
    count: number;
    ...
};

Define action as start count

let startCount = createStandardAction<WholeState> ('actionType')<DefaultPayload>();

Then in your store side reducer, combine startCount to empty action.

const reducer = createReducer<WholeState, typeof startCount>(initialState,
  builder => builder.addCase(startCount, (state, action) = {
      return {
        count: state.count   1
      }
    })
  )

full example:

let startCount = createStandardAction<WholeState> ('demo/count-started')<;DefaultPayload>();

type WholeState = {
    count: number;
};

let initialState :WholeState= {
    count: 0
};

const reducer = (state: WholeState, action: AnyAction) =>; createReducer<WholeState, typeof startCount>(initialState,
    builder => builder.addCase(startCount, (state, action) => {
        return {
            count: state.count   1
        }
    })
).caseReducer(state, action)

this work good.

  • Related