Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type 'prepare' function in redux-toolkit

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.

like image 899
Rashomon Avatar asked Aug 27 '26 13:08

Rashomon


1 Answers

    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.

like image 76
phry Avatar answered Aug 30 '26 01:08

phry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!