Search code examples
reactjsreduxreact-reduxredux-api-middleware

Debounce multiple dispatch actions


I have an autocomplete component that requires results from two separate APIs. Both APIs need to be called together with a debounced period since its an autocomplete. I am using react-redux, and redux-api. This is what I have so far. Please see the Search method that I return. Problem is only one of the calls happens.

In my AutoCompleteContainer.js

const mapDispatchToProps = dispatch => {
  const debounceDispatch = debounce(dispatch, 500);
  return {
    search(term) {
      return Promise.all([
        // Fix me! Only one of the calls below happens. 
        debounceDispatch(rest.actions.suggestions({ q: term })),
        debounceDispatch(rest.actions.concepts({ corpus: 'desc', term: [term] }))
      ]);
    },
    async reset() {
      await dispatch(rest.actions.suggestions.reset());
      await dispatch(rest.actions.concepts.reset());
    }
  };
};

Should I debounce at component level? Or can this be done here?


Solution

  • You need to have a function that dispatches both the actions, then decorate that function with debounce.

    So something like this:

    const handleAutocomplete = () => {
      dispatch(rest.actions.suggestions({ q: term })),
      dispatch(rest.actions.concepts({ corpus: 'desc', term: [term] }))
    }
    
    const debounceHandleAutocomplete = debounce(handleAutocomplete,500)