Search code examples
typescriptreduxreact-reduxredux-thunkredux-toolkit

Why am I getting typerror of "RejectwithValue" is not a function


I am trying createAsyncThunk with Typescript. On entering the catch block, I am returning rejectwithValue(param). But on console.log(action) - I am getting error -

    error:
    message: "rejectWithValue is not a function"
    name: "TypeError"
    stack: "TypeError: rejectWithValue is not a function\n    at http://localhost:3000/main.105756d7251616c1b9a2.hot-update.js:35:12"
    [[Prototype]]: Object
    meta: {arg: {…}, requestId: '2Z_7_5twR1VcGC2apgQcS', rejectedWithValue: false, requestStatus: 'rejected', aborted: false, …}
    payload: undefined
    type: "LOGIN_USER/rejected" 

This is my createAsyncthunk

export const loginUser =  createAsyncThunk(
    types.LOGIN_USER,
    async (param : {payload : object, callback : Function},  rejectWithValue : any) : Promise<AxiosResponse<any, any>> => {
        try{
            let argum : apiArgs = {
                apiUrl : '/someurl',
                method : "POST",
                payload : param.payload
            }
            const response  = await apiCall(argum)
            param.callback()
            return response.data
            
        }catch(err : any){
            return rejectWithValue(err.response.data)
        }    
    }
)

I am actually interested in the payload, which I am getting undefined due to the error.


Solution

  • See payloadCreator, the second parameter of payloadCreator function is thunkAPI object which has rejectWithValue method.

    So, it should be:

    export const loginUser = createAsyncThunk(
      types.LOGIN_USER,
      async (
        param: { payload: object; callback: Function },
        { rejectWithValue }: any
      ): Promise<AxiosResponse<any, any>> => {
        try {
          let argum: apiArgs = {
            apiUrl: '/someurl',
            method: 'POST',
            payload: param.payload,
          };
          const response = await apiCall(argum);
          param.callback();
          return response.data;
        } catch (err: any) {
          return rejectWithValue(err.response.data);
        }
      }
    );