0

I am trying to show data I get from an Axios-request. I understood, that Axios returns a Promise and I need to await, that's why it's not working here:

get categories(): Array<string> {
  let categories: Array<string> = []
  api.getORMJson().then((response) => {
    categories = response.data.nodes[0].nodes
    // Correct output
    console.log(response.data.nodes[0].nodes)
  })
  return categories
}

I already tried an approach with Promise, but that didn't work either:

get categories(): Promise<Array<string>> {
  return new Promise<Array<string>>((resolve) => {
    api.getORMJson().then((response) => {
      resolve(response.data.nodes[0].nodes)
    })
  })
}

Ultimately I want my data to be shown in a Select, like here:

<select>
  <option v-for="category in categories" :key="category" :value="category">
    {{ category }}
  </option>
</select>

EDIT: I already brought it to work once, but in a very filthy way:

@Prop({ default: [], required: true })
public categories!: Array<string>

And the getter looking like this:

get allCategories(): Array<string> {
  return this.categories
}

The problem here is, that I mutated the property directly in the mounted-Function, which looked like this:

mounted() {
      api.getORMJson().then((response) => {
        this.categories = response.data.nodes[0].nodes
      })
  }

Then I could easily iterate through allCategories and everything worked, but Vue gave me my well deserved error: "[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "categories""

  • 1
    `v-for` probably doesn't support promises. Also don't put a http request in a getter. Make the call explicitly, then store the result in a property, and have your render function deal with both states. – Bergi Apr 28 '20 at 12:51
  • categories has to be a part of vue component data and assigned as this.categories for you to be able to iterate in v-for. Can you post more code? – Luv Apr 28 '20 at 13:08
  • I edited my answer where I already did what you proposed, I think –  Apr 28 '20 at 13:16

0 Answers0