Skip to content

Instantly share code, notes, and snippets.

@markusand
Last active May 23, 2021 18:28
Show Gist options
  • Save markusand/7b2bec2ef24eb5c1d30d83660af49ed6 to your computer and use it in GitHub Desktop.
Save markusand/7b2bec2ef24eb5c1d30d83660af49ed6 to your computer and use it in GitHub Desktop.
Syntactic sugar helpers for Vuex

Vuex Saccharin

Syntactic sugar helpers to leverage Vuex usage and write less repetitive code.

📦 Install

npm i gist:7b2bec2ef24eb5c1d30d83660af49ed6

Usage

import { createStore } from 'vuex';
import { set, remove, filterBy } from 'vuex-saccharin';
import api from './services/api';

export default createStore({
  state: {
    users: [],
  },
  mutations: {
    SET_USERS: set('users'),
    REMOVE_USER: remove('users', 'id'),
  },
  actions: {
    loadUsers: async ({ commit }) => {
      const users = await api.getUsers();
      commit('SET_USERS', users);
    },
    removeUser: ({ commit }, id) => commit('REMOVE_USER', id),
  }
});
{
"version": "1.0.0",
"name": "vuex-saccharin",
"main": "vuex-saccharin.js"
}
/* GETTERS */
export const filterBy = (key, attr) => state => value => (
state[key].filter(item => item[attr] === value)
);
export const findBy = (key, attr) => state => value => (
state[key].find(item => item[attr] === value)
);
/* MUTATIONS */
export const set = key => (state, value) => { state[key] = value; };
export const toggle = key => state => { state[key] = !state[key]; };
export const push = key => (state, value) => { state[key].push(value); };
export const update = (key, id) => (state, attributes) => {
state[key] = state[key].map(item => (
item[id] === attributes[id] ? { ...item, ...attributes } : item
));
};
export const extend = (key, id) => (state, attributes) => {
const position = state[key].findIndex(item => item[id] === attributes[id]);
if (position < 0) state[key].push(attributes);
else state[key].splice(position, 1, { ...state[key][position], ...attributes });
};
export const replace = (key, id) => (state, attributes) => {
state[key] = state[key].map(item => (item[id] === attributes[id] ? attributes : item));
};
export const remove = (key, id) => (state, value) => {
state[key] = state[key].filter(item => {
const target = id ? item[id] : item;
return Array.isArray(value) ? !value.includes(target) : target !== value;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment