Skip to content

Instantly share code, notes, and snippets.

@fxmaxvl
Last active April 6, 2018 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fxmaxvl/9353355f352561376812e90cff6a8a8b to your computer and use it in GitHub Desktop.
Save fxmaxvl/9353355f352561376812e90cff6a8a8b to your computer and use it in GitHub Desktop.
import { createActionHelpers } from 'vuex-loading';
const helpers = createActionHelpers({ moduleName: 'loading' });
helpers.mapActions = actions => {
for (let [action, handler] of Object.entries(actions)) {
actions[action] = (ctx, ...rest) => {
ctx.$loading = {
startLoading: actionName => helpers.startLoading(ctx.dispatch, actionName || action),
endLoading: actionName => helpers.endLoading(ctx.dispatch, actionName || action),
};
return handler(ctx, ...rest);
};
}
return actions;
};
helpers.mapDecoratedActions = actions => {
for (let [action, handler] of Object.entries(actions)) {
actions[action] = async (ctx, ...rest) => {
helpers.startLoading(ctx.dispatch, action);
try {
return await handler(ctx, ...rest);
} finally {
helpers.endLoading(ctx.dispatch, action);
}
};
}
return actions;
};
// usage with module actions
export default {
actions: {
...helpers.mapActions({
async fetchUsefulData(ctx) {
ctx.$loading.startLoading(); // => startAction(ctx.dispatch, 'fetchUsefulData')
const data = await fetch();
ctx.commit('someCommit', data);
ctx.$loading.endLoading(); // => endAction(ctx.dispatch, 'fetchUsefulData')
}
}),
...helpers.mapDecoratedActions({
async fetchUsefulData(ctx) { // => startAction(ctx.dispatch, 'fetchUsefulData')
const data = await fetch();
ctx.commit('someCommit', data);
} // => endAction(ctx.dispatch, 'fetchUsefulData')
})
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment