After using vuex for a few months, I'm starting to question if I am utilizing it correctly.
The main issue I am facing is, How should I organize my states in a modular way?
For example:
I have a view where users can create and edit a resource (post). To create or update a post, I need to make API calls to fetch data such as the list of available categories and tags. Where should I keep this data? Should it be in vuex/modules/post.js? Or in separate modules like vuex/modules/tags.js and vuex/moduels/categories.js?
Currently, I am storing post's tags and categories in vuex/modules/post.js, but what about all the other resources needed to modify a post (like all available tags and categories that can be selected by the user)?
What about the list of posts? Should I store the list in vuex/modules/post or in its own module like vuex/modules/posts-list.js?
Should each view have its own separate module?
// vuex/modules/post.js
import Vue from 'vue';
import Axios from 'axios'
export default {
namespaced: true,
state: {
title: null,
slug: null,
tags: [],
categories: [],
meta: {},
excerpt: null,
content: null,
comments: []
},
mutations: {
SET_TITLE(state, title) {
state.title = title;
},
SET_SLUG(state, slug) {
state.slug = slug;
},
SET_EXCERPT(state, excerpt) {
state.excerpt = excerpt;
},
SET_CONTENT(state, content) {
state.excerpt = content;
},
ADD_TAG(state, tag) {
state.tags.unshift(tag)
},
REMOVE_TAG(state, index) {
Vue.delete(state.tags, index);
},
SET_TAGS(state, tags) {
state.tags = tags;
},
ADD_CATEGORY(state, category) {
state.categories.unshift(category)
},
REMOVE_CATEGORY(state, index) {
Vue.delete(state.categories, index);
},
SET_CATEGORIES(state, categories) {
state.categories = categories;
},
ADD_META(state, {key, value}) {
Vue.set(state.meta, key, value)
},
REMOVE_META(state, key) {
Vue.delete(state.meta, key);
},
UPDATE_META(state, {key, value}) {
state.meta[key] = value;
},
SET_META(state, meta) {
state.meta = meta;
}
},
actions: {
save({state}) {
Axios.post('http://myapi.com/posts', state);
},
async load({commit}, id) {
const {data} = await Axios.get(`http://myapi.com/posts/${id}`);
commit('SET_TITLE', data.title);
commit('SET_SLUG', data.slug);
commit('SET_EXCERPT', data.excerpt);
commit('SET_CONTENT', data.content);
commit('SET_TAGS', data.tags);
commit('SET_CATEGORIES', data.categories);
commit('SET_META', data.meta);
}
}
}