Search code examples
javascriptvue.jsvuejs2statevuex

Why is Vue 2 component not returning state for this computed property?


I have a Vue component that is failing to load because one of it's computed properties is undefined:

Error: Cannot read properties of undefined (reading 'map')

The computed property looks like this:

artifacts() {
  let projectArtifacts;
  if (typeof this.currentProject !== 'undefined') {
    const { artifacts } = this.currentProject.settings.artifacts;
    projectArtifacts = Object.keys(artifacts).map((name) => ({
      value: name,
      labelText: this.convertValueToLabel(name),
    }));
  } else {
    projectArtifacts = this.MIQAConfig.artifact_options.map((name) => ({
      value: name,
      labelText: this.convertValueToLabel(name),
    }));
  }
  return projectArtifacts;
},

Looking at Vue's DevTools I can see under Vuex that the array I'm seeking is in the store:

state
 currentProject: Object
  settings: Object
   artifacts: Object
     Test One: -1
     Test Two: -1

I also have under computed:

...mapState([
  'currentProject',
]),

What am I doing wrong?


Solution

  • It's because of the object destructuring error

    this expects that the artifacts object has another artifacts object in it

    const { artifacts } = this.currentProject.settings.artifacts;
    

    use:

    const { artifacts } = this.currentProject.settings;
    // or
    const artifacts = this.currentProject.settings.artifacts;