Search code examples
javascriptvue.jsrapidapi

Display API data from rapidapi in vue


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?


Solution

  • 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: []