Alexey K
Alexey K

Reputation: 6723

debounce method inside redux thunk

I have action with async method inside and I want to debounce it

export const onSearchChange = query => dispach => {
    if (query === "") {
        dispach({ type: SOME_TYPE, payload: query })
    } else {
        dispach({ type: SOME_TYPE, payload: query })
        searchProductsCall(query).then(payload => {
            dispach({ type: SOME_OTHER_TYPE, payload })
        })
    }
}

how can I debounce searchProductsCall using lodash or something else ?

Upvotes: 5

Views: 6280

Answers (1)

Narigo
Narigo

Reputation: 3101

You need to create the debounced function first and call that function instead of your searchProductsCall.

The following code should make sure the first dispatch is called right away in all cases (it probably changes the UI?) and that it calls the searchProductsCall only after the debounce and when there is a non-empty query.

export const debouncedSearchProductsCall = _.debounce((query, dispatch) => {
    if (query !== "") {
        searchProductsCall(query).then(payload => {
            dispatch({ type: SOME_OTHER_TYPE, payload })
        });
    }
}, 200);

export const onSearchChange = query => dispatch => {
    dispatch({ type: SOME_TYPE, payload: query });
    debouncedSearchProductsCall(query, dispatch);
}

Upvotes: 11

Related Questions