State is undefined in Vuex action

vuex

#1

I can see from the Vue-DevTools that the playlist state is populated, but when I destructure the state off of the context object in my action, state is undefined…

Here is the relevant code:

import PlaylistService from './api/PlaylistService'

export const state = {
  playlist: {},
  oldTitle: '',
  oldDescription: ''
}
export const actions = {
  async edit({ commit, state }, payload) {
    try {
      console.log(state) // **undefined?!?!**
      const updated = await PlaylistService.update(state.playlist.guid, {
        title: payload.title,
        description: payload.description
      })
      commit('edit', updated)
    } catch (error) {
      console.error(error)
    }
  }
}

export const mutations = {
  openEdit(state, payload) {
    state.playlist = payload
    state.oldTitle = payload.title
    state.oldDescription = payload.description
  },
  edit(state, payload) {
    state.playlist = payload
  },
  cancelEdit(state) {
    state.playlist.title = state.oldTitle
    state.playlist.description = state.oldDescription
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

Here is the Vuex state tree from the dev tools:

And then I click a save button to do a patch request, and the console.log(state) in the above action gives undefined.

I don’t know how to fix that. Any help is appreciated. Thanks.


#2

Try exporting each constant as part of the default, rather than individually… and as default. I imagine that’d cause an issue.

const state = {}
const mutations = {}
const actions = {}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

#3

Errrrr. It was something totally unrelated actually. So, I’ve no idea why the console.log was saying that the state was undefined, but I was getting an error from my endpoint because the guid was not being added. Well, turns out that I wasn’t adding the guid in the PlaylistService.update function definition itself, even though I was sending the guid in.

So, it’s still weird that the console.log is saying state is undefined, and actually even weirder that if I do console.log(state.playlist) THEN I get output…

But the code works at least lol