[Vuejs]-Getting an array from an API response

0👍

So, multiple things going on here.

  1. Requesting random/jokes gives only one joke as an object. requesting random/jokes/:count is used for multiple jokes in an array.
  2. You’re replacing the state of this.jokes with the data object returned from the API, therefore v-for is repeating the markup for each key on the object. This causes it to generate the same HTML 4 times, because there are 4 keys.

In order to fix it, you either have to get multiple jokes at the same time by calling the right endpoint, or you should modify your axios call so that the object received from the API is pushed into the array, like so:

axios
      .get(
        "https://us-central1-dadsofunny.cloudfunctions.net/DadJokes/random/jokes",
        {
          headers: {
            Accept: "application/json"
          },
          params: {
            limit: 1
          }
        }
      )
.then(response => {
        this.jokes.push(response.data);
      })

0👍

If you look at the documentation,

/random/jokes returns one joke

/random/jokes/:count returns :count jokes

Therefore, you could change your code to something like below:

methods: {
    getNJokes(n) {
        axios.get(`https://us-central1-dadsofunny.cloudfunctions.net/DadJokes/random/jokes/${n || 1}`, { headers: { Accept: "application/json" } })
             .then(response => {
                 this.jokes = response.data;
             })
             .catch(err => {
                 alert(err);
             });
    }
},
created() {
    this.getNJokes(3);
}

Then in your template, it should be joke.setup and joke.punchline instead of jokes.setup and jokes.punchline.

<p>{{joke.setup}}</p>
<p>{{joke.punchline}}</p>

Then if you want a button to get an additional joke:

<button type="button" @click="getNJokes(1)">Get Different Joke</button>
Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
  el: "#app",
  data: () => {
    return {
      jokes: []
    }
  },
  methods: {
    getNJokes(n) {
      axios.get(`https://us-central1-dadsofunny.cloudfunctions.net/DadJokes/random/jokes/${n || 1}`, {
          headers: {
            Accept: "application/json"
          }
        })
        .then(response => {
            this.jokes = response.data;
        })
        .catch(err => {
          alert(err);
        });
    }
  },
  created() {
    this.getNJokes(1);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="joke in jokes">
    <p><strong>{{joke.setup}}</strong> {{joke.punchline}}</p>
  </div>
  
  <button @click="getNJokes(1)">Get Another Joke</button>
</div>

Leave a comment