Search code examples
react-hooksreact-reduxredux-thunkredux-toolkitreact-tsx

Debounce in Redux Toolkit


I'm Trying to debounce below API call with using lodash debounce

export const getProfile = createAsyncThunk(
  GET_PROFILE,
  async (amount: any, { rejectWithValue }: any) => {
    try {
      const response = await API.Get(EndPoint.GET_PROFILE)
      console.log(response)
      return response.data
    } catch (error: any) {
      amount.failCallBack(error?.response?.data?.msg || 'something_went_wrong')
      return rejectWithValue(error?.code || 'Something went wrong..!')
    }
  }
)

above function is worked without any errors and fetch data able to see inside fulfilled of the action

so I tried to implement debounce as below way

export const getProfile = createAsyncThunk(
  GET_PROFILE,
  debounce(async (amount: any, { rejectWithValue }: any) => {
    try {
      const response = await API.Get(EndPoint.GET_PROFILE)
      console.log(response)
      return response.data
    } catch (error: any) {
      amount.failCallBack(error?.response?.data?.msg || 'something_went_wrong')
      return rejectWithValue(error?.code || 'Something went wrong..!')
    }
  }, 5000)
)

Now there is no any exceptions in web app and when I console.log the fulfilled action it shows payload as undefined

{
    "type": "login/getProfile/fulfilled",
    "meta": {
        "arg": {
            "data": "login"
        },
        payload: undefined,
        "requestId": "8pfalpIzFl8nNOgi2jRcb",
        "requestStatus": "fulfilled"
    }
}

any suggestions for fix this issue.

thanks in advance


Solution

  • Don't debounce the payload creator - debounce dispatching the thunk action. And since you probably don't want to that in your component, do it in a manual thunk

    const getProfile = createAsyncThunk( ... normal definition ... );
    const debounced = debounce((arg, dispatch) => dispatch(getProfile(arg)), 5000);
    const debouncedGetProfile = (arg) => (dispatch) => debounced(arg, dispatch)
    

    and then use that

    dispatch(debouncedGetProfile(amount))