Search code examples
vue.jsvuex

sub-property write commit withing store actions using vuex-pathify make.mutations


Here is how my store looks like:

const state = {
    user: {
        profile: {
            phoneNumber: '',
        }
    }
}

const mutations = make.mutations(state)

const actions = {
    submitPhoneNumber({commit}, phone_number) {
        // blah blah
        commit('[email protected]', phone_number);
    }
}

But no such mutation can be found. Maybe I could import store.js within store.js and use the set helper but I believe things can get pretty creepy specially because of the (In my opinion poor) design decision that the library creator has made to combine commit and dispatch (I believe being explicit would have been much better here)


Solution

  • Pathify author here.

    You can't commit a mutation with sub-property syntax using Vuex mutations, because Vuex will treat it as a string.

    You are correct that you would need to use store.set() to do this.

    You can be explicit with commits and dispatches by appending a ! to the call. This is called "direct syntax":

    To commit directly using the sub-property syntax, use the Payload class:

    Something like this should work:

    import { Payload } from 'vuex-pathify'
    commit('SET_USER', new Payload('SET_USER', @profile.phoneNumber', phone_number);
    

    Looks like I haven't documented this, so I have a made a ticket here:

    It's using a commit from a component, but should work just the same.

    People have asked before if it would be possible to use Pathify-style commits in actions and I said it wasn't, but I've just thought of something that might make it possible.

    Follow this feature request for more info: