Categories
javascript vue.js vuex

Where should I put state initialization code in Vuex?

Should Vuex store keep only the code of state structure and how to modify that state (mutations, actions), or also the actual state initialization and values?

I started wondering about it, when my state initialization code become more complex, because I don’t see any natural place in Vuex architecture to put this code into.

Let’s say I have such a store:

export default {
state: {
list: []
},
mutations: {
addItem(state, { item }) {
state.list.push(item);
}
}
}

If the list starts empty, it’s enough. But what if I have default values for the list and also want to store the list in LocalStorage, so that I can preserve it’s value between page loads.

const STORAGE_LIST_KEY = 'list';
const LIST_DEFAULT = [
{
id: 1,
name: 'item 1'
},
{
id: 33,
name: 'item 33'
}
];
function initializeList() {
let savedList = localStorage.getItem(STORAGE_LIST_KEY);
return savedList ? savedList : LIST_DEFAULT;
];

Is there some natural place in the Vuex store architecture, where I should put initializeList() function? (e.g. In a Vue component I would put initializeList() into methods part of the component) Or maybe the store is just about the structure and the initialization code belongs to the Vue components?