Search code examples
vue.jsvuexgetter

Vuex getter does not react on state change


I have a code which need to get some processed values from Vuex store. So I wrote getter which should return processed values. The code looks like:

    mediaSettings: (state) => {
        const timestamps = [];
        const events = [];

        state.media.forEach( medium => {
            if( !medium.settings || !medium.settings.dates ) return;

            medium.settings.dates.forEach( dateRange => {
                if( !dateRange.date_from || !dateRange.date_to ) return;

                const from = new Date( dateRange.date_from );
                const to = new Date( dateRange.date_to );
                while ( from <= to ) {
                    if( timestamps.includes(from.getTime()) ) {
                        from.setDate( from.getDate() + 1 );
                        continue;
                    }

                    events.push({
                        date: new Date( from.getTime() ),  // Need Date clone via new Date().
                        mediumId: medium.id,
                    });
                    timestamps.push( from.getTime() );
                    from.setDate( from.getDate() + 1 );
                };
            });
        });
        return events;
    }

This is the muttation which change the values:

SET_MEDIA_SETTINGS(state, payload) {
    state.media.forEach( medium => {
        if( medium.id === payload.media_id ) {
            medium.settings = { timeMode: payload.mode, dates: payload.dates, times: payload.times };
        }
    });
},

The problem is that Vuex does not react when state.media[].settings.dates[] values are changed. The change should happened on state.media[] level. How can I fix it? What is the workaround for this issue? Thanks for help.


Solution

  • The solution for this was to use Vue set() method to change the value in mutation. The code is here:

    SET_MEDIA_SETTINGS(state, payload) {
        state.media.forEach( (medium, index) => {
            if( medium.id === payload.media_id ) {
                medium.settings = { timeMode: payload.mode, dates: payload.dates, times: payload.times };
                this._vm.$set(state.media, index, {...medium});
            }
        });
    },