How to use debounce with Vuex?

Viewed 730

I am trying to debounce a method within a Vuex action that requires an external API.

// Vuex action:

async load ({ state, commit, dispatch }) {
  const params = {
    period: state.option.period,
    from: state.option.from,
    to: state.option.to
  }

  commit('SET_EVENTS_LOADING', true)
  const res = loadDebounced.bind(this)
  const data = await res(params)
  console.log(data)


  commit('SET_EVENTS', data.collection)
  commit('SET_PAGINATION', data.pagination)
  commit('SET_EVENTS_LOADING', false)

  return data
}



// Debounced method

const loadDebounced = () => {

  return debounce(async (params) => {
    const { data } = await this.$axios.get('events', { params })
    return data
  }, 3000)

}

The output of the log is:

[Function] {                                                                                                                                                                                                           
  cancel: [Function]
}

It is not actually executing the debounced function, but returning to me another function.

1 Answers

I would like to present a custom debounce method which you can use in your vuex store as

let ongoingRequest = undefined;
const loadDebounced = () => {
    clearTimeout(ongoingRequest);
    ongoingRequest = setTimeout(_ => {
        axios.get(<<your URL>>).then(({ data }) => data);
    }, 3000);
}

This method first ensures to cancel any ongoing setTimeout in the pipeline and then executes it again.

This can be seen in action HERE

Related