Vuex freezes on bulk mutations

Viewed 1384

I have the following Vuex store that I use to store chart objects retrieved from my backend using Axios.

const getters = {
    charts( state ) { return _.without( state.charts, undefined ); },
    chart( state ) { return id => state.charts.find( c => { return c.id === id; } ) }
}
const actions = {
    getCharts( { commit, rootState } ) {
        // Load data from server
        return api.get( rootState.Laravel.api_url + '/chart' )
            .then( ( response ) => { 
                // Store the returned data
                _.forEach( response.data.data, function( chart ) {
                    commit( 'STORE_CHART', chart );
                });
            })
            .catch( ( error ) => console.log( error ) );
    }
}
const mutations = {
    STORE_CHART( state, chart ) {
        Vue.set( state.charts, chart.id, Object.freeze( chart ) );
    }
}

The store works fine, but as soon as I open the VueDevtools and call getCharts() again, the whole browser freezes. I guess this is because I'm updating the store in bulk and the devtools can't track all these changes (150 - 200 objects).

Is there something I'm doing wrong? Is there a better way to bulk update objects in a Vuex store?

1 Answers

Instead of commuting a mutation for each chart in your forEach() you can directly pass the response.data.data as a payload to STORE_CHART` mutation and apply the forEach in the mutation itself

const actions = {
    getCharts( { commit, rootState } ) {
        // Load data from server
        return api.get( rootState.Laravel.api_url + '/chart' )
            .then( ( response ) => { 
                // Store the returned data
                commit( 'STORE_CHART', response.data.data );
            })
            .catch( ( error ) => console.log( error ) );
    }
}
const mutations = {
    STORE_CHART( state, charts ) {
          _.forEach( charts, function( chart ) {
                Vue.set( state.charts, chart.id, Object.freeze( chart ) );
          });
    }
} 
Related