Im trying to debounce a api action which is a dispatch call to reducer.The api call in the browser should debounce after a particular delay given as a single api , but its going as multiple api calls after the delay ,the code is as follows.
please refer the screenshot also

const apiCall = (args) => {
dispatch(getECByStatus({status: 'PENDING_APPROVAL', search: args}))
}
const debounce = (apiFunc, delay) => {
let inDebounce
return function () {
const context = this
const args = arguments
clearTimeout(inDebounce)
inDebounce = setTimeout(() => {
inDebounce = null
apiFunc.apply(context, args)
},delay);
}
}
const optimizedVersion = debounce(apiCall, 600)
const handleSearchChange = (value) => {
optimizedVersion(value)
}
the handleSearchChange is the onchange event fired from the input box on typing the input.getECByStatus is a redux action creator, which calls api with the search param,
export const getECByStatus = (params) => async (dispatch) => {
let editCheckType = params?.type ? `/${params.type}` : ''
let searchParams = params?.search ? `&search=${params.search}` : ''
try {
dispatch({
type: actionType.GET_EC_BY_STATUS_REQUEST,
payload: {
load: true,
},
})
let study_id = getItem('study_id')
const { data } = await DataService.get(
`/edit-checks${editCheckType}?status=${params.status}&study_id=${study_id}${searchParams}`
)
dispatch({
type: actionType.GET_EC_BY_STATUS_SUCCESS,
payload: {
load: false,
data: data.data,
}
},
})
} catch (error) {
console.error('Get EC by status error', error)
dispatch({
type: actionType.GET_EC_BY_STATUS_FAIL,
payload: {
load: false,
},
})
}
}
Thanks in advance!
This is due to the UI re-render after dispatch event get fired, since the input box is a controlled one , we have to pass the updated value to the input box component, so we can make pass a ref for not re-rendering the UI.