1

I'm trying to consume an API using axios.

This is my code until now:

<select>
    <option v-for="value in values"> value.name </option>
</select>

   // js
   data(){
        values: [],
   },
   created() {
        this.getData();
   },

   methods: {
       getData: () => {
          axios.get('url')
          .then(res => {
              this.value = res.data.dados;
              console.log(res.data.dados);
          })
          .catch(error => {
               console.log(error);
          });
   }
}

The promise's console.log is working normally, but the options with data isn't rendered. It's probably because my select component is being rendered before the 'getData()'. How can I fix it?

2 Answers 2

2

Just put a loading handler.

<select v-if="loaded">
  <option v-for="value in values"> value.name </option>
</select>

   // js
   data(){
        values: [],
        loaded: false,
   },
   created() {
        this.getData();
   },

   methods: {
       getData: () => {
          axios.get('url')
          .then(res => {
              this.value = res.data.dados;
              this.loaded = true;
          })
          .catch(error => {
               console.log(error);
               this.loaded = true;
          });
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You've a typo on this.value, it should be this.values. If that doesn't work, use this.$forceUpdate() to force re-render component

<select>
    <option v-for="value in values">{{ value.name }}</option>
</select>

   // js
   data(){
        values: [],
   },
   created() {
        this.getData();
   },

   methods: {
       getData: () => {
          axios.get('url')
          .then(res => {
              this.values = res.data.dados; // change value to values
              console.log(res.data.dados);
              this.$forceUpdate(); // add forceUpdate
          })
          .catch(error => {
               console.log(error);
          });
   }
}

3 Comments

It was not the typo. Now, it says "TypeError: _this.$forceUpdate is not a function at eval (Pesquisa.vue?cddd:49)"
have you try change the this.value to this.values ?
oh the forceUpdate error because the function called upon created, you can change it to mounted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.