Retrieving an array of data from an API's response

I'm currently working on a dad jokes generator project using Vuejs and integrating it with this API . However, I've encountered an issue where I'm receiving the same joke repeated in an array instead of just one unique joke. You can view the problem in this screenshot: . Additionally, I'm trying to implement a button that triggers the fetch function, but I've hit a roadblock while working with the axios library.

<script>
import axios from "axios";
export default {
  name: "Jokes",
  data() {
    return {
      jokes: []
    };
  },
  methods: {},
  created() {
    axios
      .get(
        "https://us-central1-dadsofunny.cloudfunctions.net/DadJokes/random/jokes",
        {
          headers: {
            Accept: "application/json"
          },
          params: {
            limit: 1
          }
        }
      )
      .then(response => {
        this.jokes = response.data;
        console.log(response.data);
      })
      .catch(err => {
        alert(err);
      });
  }
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div id="jokes-card">
    <div v-for="joke in jokes" :key="joke.id">
      <p>{{jokes.setup}}</p>
      <p>{{jokes.punchline}}</p>
    </div>
  </div>
</template>

Answer №1

There are several things happening here.

  1. When requesting random/jokes, only one joke is returned as an object. If you want multiple jokes in an array, you should use the endpoint random/jokes/:count.
  2. You are replacing the state of this.jokes with the data object from the API, causing the v-for directive to repeat the markup for each key in the object. This leads to the same HTML being generated 4 times due to there being 4 keys.

To resolve this issue, you can either fetch multiple jokes at once by using the correct endpoint or update your axios call so that the object received from the API is added to the array like this:

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);
      })

Answer №2

By referring to the documentation,

/random/jokes gives you one joke

/random/jokes/:count provides :count number of jokes

With that in mind, you can adjust your code like so:

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

Then in your template, use joke.setup and joke.punchline instead of jokes.setup and jokes.punchline.

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

If you wish to have a button for fetching another joke:

<button type="button" @click="fetchNJokes(1)">Get Another Joke</button>

Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
  el: "#app",
  data: () => {
    return {
      jokes: []
    }
  },
  methods: {
    fetchNJokes(amount) {
      axios.get(`https://us-central1-dadsofunny.cloudfunctions.net/DadJokes/random/jokes/${amount || 1}`, {
          headers: {
            Accept: "application/json"
          }
        })
        .then(response => {
            this.jokes = response.data;
        })
        .catch(err => {
          alert(err);
        });
    }
  },
  created() {
    this.fetchNJokes(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="fetchNJokes(1)">Get Another Joke</button>
</div>

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

What is the method for arranging by oldest and newest based on date?

I need help organizing my presentation with a variety of books. How can I sort them from oldest to newest? const userBooks = [ { id: 1, name: "", author: "", genre: "", date: "2022-1-12", }, ...

Steps for launching a Vuetify dialog box once a user successfully signs into the application

I have an idea for my application where I want to display a modal to guide new users when they first log in. To accomplish this, I am storing a variable called isNewUser in the global state and using it to determine whether the modal should be shown or not ...

What could be preventing the webpack dev server from launching my express server?

Currently working on a straightforward web application using express and react. The front-end React bundle is being served via the express server. Everything runs smoothly with my start script, which builds the front-end code and launches the express serv ...

What might be causing my list item to execute functions that it shouldn't be?

Greetings! I've recently developed a list component in React Native specifically for my settings page. My goal is for each component on the settings page to have a function, although in some cases it may not be necessary. To achieve this, I have set ...

Is there a way to launch QTP from JavaScript without relying on ActiveXObject?

Is there a way to call QTP from JavaScript without relying on ActiveXObject? I would appreciate any guidance on how to accomplish this task. Thanks in advance, Ramya. ...

Tips for breaking up array elements across multiple "tr" tags

In this particular example, I have a Fiddle set up with multiple tr elements displayed within an ng-repeat. My goal is to have three td elements per row. Would it be necessary to use an inner angularjs ng-repeat and split the iconDets array for this purpos ...

What is the reason for the visibility of my API key when utilizing next.js alongside environment variables?

I recently went through the next.js documentation and implemented a custom API key on my now server. However, I encountered an issue where when I execute now dev and navigate to the sources tab, my API key is visible. https://i.stack.imgur.com/kZvo9.jpg ...

Transform "<Mutation>" to useMutation

In my removeUser page, I have implemented a < Mutation > and handled errors using the submitForm() function. The initial code worked perfectly: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); con ...

Unable to assign the "innerHTML" property to a string

Currently, I am working on developing an Issue Tracker with two main functions. The first function, saveIssue(), is responsible for saving submitted issues to localStorage triggered by the submit eventListener. The second function, fetchIssues(), retriev ...

Show the data from the chosen array using Vue JS

Just diving into Vue JS and eager to master it through creating a simple note-taking app. The concept is straightforward - a list of all notes (their titles) on the left, and when you click on a note title, the corresponding note text is displayed in a te ...

Material-UI exclusively incorporates specific components

Is there a way to include Material UI dialogs in my project without having to install the full Material UI library? I only need the dialogs component and don't want any other components included. Any suggestions or help on how to achieve this would be ...

Accessing information from a JSON array

I am encountering difficulties in fetching data from a JSON file. Whenever I click the button, it triggers the call function which then retrieves data from the json.jsp file containing an array. However, I am unable to retrieve the data successfully. Below ...

Activate an event on a separate webpage using jQuery or JavaScript

Currently, I am in the process of working on a project with 2 distinct pages: Index Settings On the Settings page, I have implemented a button to close an element and hide it. However, I am encountering an issue where I want the elements on the Index pa ...

The next button will only activate once all input forms have been completed in multiple forms

In the JavaScript code: var current_fs, next_fs, previous_fs; //fieldsets var left, opacity, scale; //fieldset properties that will be animated var animating; //flag to prevent rapid glitches from multi-clicking $(".next").click(function(){ if(animati ...

When the forward button is pressed multiple times in the carousel, the alignment changes

I recently noticed that the alignment of my carousel gets disturbed when I repeatedly click the forward button (>). How can I ensure that the carousel moves smoothly one item at a time when I click the forward or backward buttons? <div class="contai ...

What is the best way to incorporate a fadeIn animation to a text in jQuery?

Looking for help with appending the fadeIn() jQuery function to a string that increments an integer within a paragraph. I attempted concatenation without success. Any recommendations on how to solve this issue? $p.text(parseInt($p.text(),10) + 1); ...

Is there a way to replace the standard Apache login/password popup box with a customized one using a combination of JavaScript, HTML

Is there a way to customize the default Apache login box with a custom design using JavaScript, HTML, and PHP? Thank you! ...

JavaScript Multiplicative Persistence Problem Resolved by Implementing Efficient Solution that Executes in a Timely

I am currently facing an issue with the following problem: Your task is to create a function called persistence, which takes a positive parameter num and calculates its multiplicative persistence. Multiplicative persistence refers to the number of times y ...

Is it possible for a browser to debug a JavaScript function automatically even if there are no errors present in the function?

While it's common knowledge that browsers can debug JavaScript functions that have errors, is there a way to debug a JavaScript function that doesn't have any errors? For instance, if I have a JavaScript function in my button control that runs wi ...

Displaying a dialog or popup in React Native when catching errors

Exploring React Native has been quite a journey for me, especially when trying to implement a popup for error handling. Despite numerous attempts, I haven't been successful in getting it to work as desired. The code snippet below captures my current i ...