2

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 fullfilled 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 fullfilled 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

Chanaka
  • 760
  • 1
  • 10
  • 21

1 Answers1

2

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))
phry
  • 35,762
  • 5
  • 67
  • 81
  • Worked like a charm. You could fix the missing parenthesis on the second line. – hlustosa Jan 05 '23 at 18:59
  • @hlustosa good catch, fixed it. – phry Jan 05 '23 at 22:09
  • `Don't debounce the payload creator - debounce dispatching the thunk action` @phry why is this approach preferred over debouncing within the redux store / thunk? I am trying to justify why every dispatcher should need to care about debouncing the actions it emits, seems less clean / scalable. Example alternative: https://gist.github.com/sarakusha/bb63f1a4a0143afc257eca57f2acc5f2 – dclaze Mar 31 '23 at 00:21
  • @dclaze building a manual solution around this will probably make it better, but you will still end up with a ton of unnecessary actions flying around that might clobber your action log. I'd personally try to avoid that if it nicely can be avoided. But I agree, your solution works over multiple components, which is nice. – phry Mar 31 '23 at 14:00