[Vuejs]-Is it possible to enque commits to send in batch insted of one by one in vuex?

0đź‘Ť

âś…

One of my coworkers (https://stackoverflow.com/users/story/10724336) was able to implement the solution of debounce queue… Here’s the solution:

My action:

function evaluationMaterial({ commit }, { materialId, evaluationState }) {
    _updateInteractionStateDebounced({ commit, materialId, evaluationState });
}

The _updateInteractionStateDebounced fuction:

const _updateInteractionStateDebounced = debounceQueueUtil.debouncedQueue(_updateInteractionState);

The debounceQueueUtil function:

const debouncedQueue = function(functionToBeCalled, timeout = 300) {
    const self = {};

    self.daleyedArgs = [];
    self.timeout = timeout;
    self.functionToBeCalled = functionToBeCalled;

    return _saveArgs.bind(self);
};

const _saveArgs = function(args) {
    if (this.debounced) {
        clearTimeout(this.debounced);
    }

    this.daleyedArgs.push(args);
    this.debounced = setTimeout(_callDebouncedFunction.bind(this), this.timeout);
};

const _callDebouncedFunction = function() {
    const args = this.daleyedArgs;
    this.daleyedArgs = [];

    this.functionToBeCalled(args);
};

export default {
    debouncedQueue
};

0đź‘Ť

  1. Use an asynchronous action instead of commit.
  2. Gather promises from your operations and await on Promise.all()
  3. Then update your store as a batch of commits.

0đź‘Ť

The idea of vuex is to make “trackable” all of those commits.
If you want to have a cleaner commit history you would need to create a special commit to wrap all of those changes into one or make your component not to trigger so many actions/commits by buffering them. If those changes come from different actions and need to be applied right away, then you’re out of luck.

Leave a comment