简体   繁体   中英

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 ?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM