Search code examples
ecmascript-6vuejs2vuex

Vuex: committing an object then finding it by ID


I'm trying to commit something to my Vuex state using this method.

getVariableLookup: ({ commit, _state }, payload) => {
  http.get(`/frame_variables/${payload}`)
    .then(response => {
      commit('addVariableLookup', response.data.frame_variable.body)
    })
}

This works fine, but I want to store the payload alongside the response. I cannot seem to commit it as an object like so.

commit('addVariableLookup', { id: payload, body: response.data.frame_variable.body })

That method returns this:

weird log

Update

Turns out it was setting the data fine, I just can't retrieve it with this code:

const body = this.variableLookups.find(x => x.id === v.v_id)

this.variableLookups returns them all. How can I find the individual object?


Solution

  • Grabbing the body for the relevant id should be just:

    const entry = this.variableLookups.find(x => x.id === v.v_id)
    const body = entry ? entry.body : null
    

    Whether the ternary/null are required would depend on whether you already have logic to prevent that case occurring. You will need to be careful to wait until after the action has loaded the data before you try to grab it.

    What you're doing might be better achieved using an object to map the ids to the bodies, rather than using an array. The usual caveat around adding properties to objects applies.