0

I'm playing around with vueJS and rapidapi and I'm trying to display data from an API using vue and retrieving the API using JS Fetch method. However, when I run the code all I got was the value that initiated it (which is: []).

<template>
  <div>
    <div>{{ chuckData }}</div>
  </div>
</template>

<script>
var chuck = [];
fetch("https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random", {
  method: "GET",
  headers: {
    "x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
    "x-rapidapi-key": "***"
  }
})
  .then(response => response.json()) // Getting the actual response data
  .then(data => {
    chuck = data;
  })
  .catch(err => {
    console.log(err);
  });

export default {
  data() {
    return {
      chuckData: chuck
    };
  }
};
</script>

I also tried to use the following:

var chuck fetch("https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random", {...}

But all I got was [object Promise] without the data that I'm expecting to display.

What am I doing wrong?

Grokify
  • 15,092
  • 6
  • 60
  • 81
Artvader
  • 906
  • 2
  • 15
  • 31

2 Answers2

1

You should define a method in the Vue instance that gets your API data.

Like this:

methods: {
    getRapidApiData() {
        //do the fetch.... etc
    }
}

You can get rid of var chuck = []; because it's not needed and replace references of chuck with this.chuckData.

You can then initiate chuckData like chuckData: []

Shoejep
  • 4,414
  • 4
  • 22
  • 26
0

The final solution looks something like this:

<div class="col-md-3" v-for="result in chuck">
         {{result}}
</div>

<script>
export default {
  data() {
    return {
      chuck: []
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
    fetch("https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random", {
      method: "GET",
      headers: {
        "x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
        "x-rapidapi-key": "<API KEY>"
      }
    })
      .then(response => response.json())
      .then(data => {
        this.chuck = data;
      });
    }
  }
};
</script>

Thanks!

Artvader
  • 906
  • 2
  • 15
  • 31