Utilize Vue to showcase data from the RapidAPI interface

Experimenting with vueJS and rapidapi led me to a challenge: displaying data from an API using vue and the JS Fetch method. Unfortunately, all I could see when running the code was the initial value ([]).

<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()) // Accessing actual response data
  .then(data => {
    chuck = data;
  })
  .catch(err => {
    console.log(err);
  });

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

Another attempt was made:

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

However, the outcome was [object Promise] instead of the intended data for display.

What steps should be taken to rectify this issue?

Answer №1

To efficiently retrieve data from your API, it is recommended to create a method within the Vue instance.

Here's an example:

methods: {
    fetchDataFromAPI() {
        //perform API call.... etc
    }
}

You can remove var chuck = []; as it is unnecessary and update all instances of chuck with this.chuckData.

Initialize chuckData like this: chuckData: []

Answer №2

Here is the finalized code snippet:

<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>

Many thanks!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a combination of different materials on a single mesh can lead to problems with z-index and clipping

Currently in my threejs project, I am attempting to apply two different materials to a mesh. One material has a solid color, while the other has a canvas texture. To achieve this, I have created both materials and added them to an array, which is then assi ...

Function call fails when parameters are passed

I've been grappling with this conundrum for a few weeks now, on and off. Perhaps someone else will spot the glaringly obvious thing that I seem to be overlooking. At the present moment, my primary goal is to simply confirm that the function is operat ...

I'm having trouble getting Socket.io to function properly with my Node/Express application

Using openshift with express, I have been experiencing difficulties configuring socket.io. No matter what adjustments I make, it seems to disrupt my application. What could be the issue? Interestingly, when I disable the sections related to socket.io, the ...

Tips for utilizing JSON.parse

Within my ajax request, I am encountering the following code: 403: function(jqXHR) { var error = jqXHR.responseText; console.log(error); } When this error occurs, a message is displayed in the console: Htt ...

Guide on toggling visibility of a column in Material-ui based on a conditional statement

Can someone help me with code that allows me to hide or show the TableCell based on an if statement? I am currently working with MATERIAL-UI framework which can be found here: https://material-ui.com/ <TableBody> {Object.entries(servicesCode).map ...

Hiding elements in HTML by setting their display property to "

I'm struggling with this code: <div id="affichageRecherche"></div> <div class="row px-xl-9 d-flex justify-content-start" id="affichageCatalogue">(lot of code)</div> At the bottom of the page ...

MongoDB Sorting Techniques

I'm struggling to figure out how to retrieve an ordered list from MongoDB data. I need to fetch the results from a Mongo collection using return and .find(), structured like this: For instance, let's say I have one collection for cars with 10 do ...

Revamping the Look: Refreshing Background of Div

I'm attempting to change the background image of the body element on a webpage when I hover over links with data-* attributes. It's working perfectly, but I can't seem to figure out how to create a smooth fade between the images when a link ...

Generate checkboxes by utilizing the JSON data

Here is a snippet of my JSON data: [ { "type": "quant", "name": "horizontalError", "prop": [ 0.12, 12.9 ] }, { "type": "categor", "name": "magType", "prop": [ ...

update the componentWillMount() function

I am currently exploring the code found at https://github.com/Spyna/react-store/blob/master/src/createStore.js What adjustments do I need to make in order to align with the deprecated componentWillMount lifecycle method? CreateStore const createStore = ...

Searching Firestore arrays for objects based on one of two fields

Within my document, I am working with the following array: https://i.sstatic.net/j9hBT.png I have a SizeFilterComponent that emits a BaseFilter object when a size is selected. Multiple sizes can be selected. Here is the method handling this logic: selecti ...

Is the neglected property being discarded?

First things first, let's talk about my class: class FavoriteFooBar { ... isPreferred: boolean = false; constructor() { this.isPreferred = false; } } Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to pr ...

Loading images lazily using knockout.js

I have been working on implementing lazy loading for images using knockoutjs binding. I previously successfully implemented lazy loading without the knockoutjs framework, but I am unsure of how to achieve this with knockoutjs binding. Below is my HTML code ...

What is the best way to display various components on a single page?

Every user type within my app requires a unique dashboard. Currently, the admin vue appears as follows: <template> <main id="admin-main"> <header id="admin-dashboard-header" class="jumbotron"> <div> ...

When attempting to click on my subtopics using jQuery, they do not appear as expected

$(document).ready(function () { $("#subTopics").hide(); $("#mainTopics").click(function () { $("#subTopics").show("slow"); }); }); body { margin: 0; } li, a{ text-decoration: none; list-style-type: none; text-d ...

Modify the information on a page by clicking a button on a different page

I'm currently working on the design of a website that consists of two pages. The first page features a button, which when clicked should remove the hidden class from an element on the second page. I have searched extensively for a solution, but so far ...

Is it a good idea to steer clear of including OAuth tokens in the

Utilizing my OAuth2 token in my API program is essential. However, I am also keen on sharing my code through GitHub. How can I securely use my confidential token without including it directly in my source code? ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

Tips for adding a CSS class to an HTML element on-the-fly

As a newcomer to JavaScript and AngularJS, my question may be considered naive by some. I am currently working on a tutorial project involving AngularJS. Here is the HTML code snippet I am dealing with: <link href="http://netdna.bootstrapcdn.com/boo ...

What is a more efficient method for structuring this React page while making an asynchronous request to the API?

When developing, I encountered this scenario where I needed to ensure that a certain useEffect function only runs once. To achieve this, I established router.query.something as a dependency for the effect. The logic is such that the request will only trigg ...