user234562
user234562

Reputation: 627

Merge two states in Vuex store

I have a Vuex store with two states.

I am using these states to show the notes in a list with a getter. This getter merges the two objects and return the merge objects

The problem I have now is that if I add a new note to one of the states it will not be shown in the note list because the getter doesn't pick the 'change' up. I think this happens because I return a variable instead of a function.

This is my getter:

const getters = {
    notesObject: (state, getters, rootState, rootGetters) => {
        let result = {};
        let mergedObject = {...state.notes, ...state.localNotes};
        Object.keys(mergedObject).forEach(key => {
            const item = mergedObject[key];
            if (rootGetters['tags/activeKey'] === null) {
                result[key] = item
            } else if (item.tag_id === rootGetters['tags/activeKey']) {
                result[key] = item
            }
        });
        return result;
    },
};

Example object:

example: {
            5: {
                title: 'Testing title',
                text: 'text'
            },
            6: {
                title: 'Testing title',
                text: 'text'
            }
        }

I hope someone can help me out to find the best solution for this. I was thinking about using a watcher, but I know these need to be avoided.

A solution was to let the watcher merge the two states into a new state. Then the getter doesn't have to merge the two objects

Upvotes: 3

Views: 4179

Answers (1)

Connor
Connor

Reputation: 64644

Vue's reactivity system doesn't detect adding new properties. Try using Vue.set(object, key, value) when adding new notes.

In your mutation function replace state.localObject[payload.id] = payload; with Vue.set(state.localObject, payload.id, payload); The getter should then work properly.

Upvotes: 6

Related Questions