Trouble showing data from external API in Vue application

Hey everyone! I’m new to Vue and I’m trying to get some data from an external API to show up on my page. I’m using the Fetch API to make the request, but I’m having some issues.

Here’s what I’ve got so far:

<template>
  <div>
    <p>{{ jokeData }}</p>
  </div>
</template>

<script>
let joke = [];

fetch('https://example-joke-api.com/random', {
  headers: {
    'api-key': 'my-secret-key'
  }
})
.then(res => res.json())
.then(data => {
  joke = data;
})
.catch(error => {
  console.error('Oops!', error);
});

export default {
  data() {
    return {
      jokeData: joke
    };
  }
}
</script>

When I run this, all I see is an empty array. I’ve also tried assigning the fetch directly to a variable, but then I just get ‘[object Promise]’ instead of the actual joke.

What am I doing wrong here? How can I get the joke to show up on the page? Thanks for any help!

While the previous answer provides a solid solution, I’d like to offer an alternative approach using async/await. This can make your code more readable and easier to handle errors:

export default {
  data() {
    return {
      jokeData: '',
      error: null
    };
  },
  async mounted() {
    try {
      const response = await fetch('https://example-joke-api.com/random', {
        headers: { 'api-key': 'my-secret-key' }
      });
      if (!response.ok) throw new Error('Network response was not ok');
      const data = await response.json();
      this.jokeData = data;
    } catch (err) {
      this.error = 'Failed to fetch joke: ' + err.message;
      console.error('Error:', err);
    }
  }
}

This method handles errors more gracefully and allows you to display an error message to the user if the fetch fails. Remember to add error handling in your template as well.

I’ve encountered similar issues when working with external APIs in Vue. The problem here is that the fetch operation is asynchronous, but you’re not handling it correctly within the Vue component lifecycle.

Here’s what I’d suggest based on my experience:

  1. Move the fetch call into a method.
  2. Call this method in the created() or mounted() lifecycle hook.
  3. Use a data property to store the joke and update it when the fetch resolves.

Something like this:

export default {
  data() {
    return {
      jokeData: ""
    };
  },
  methods: {
    fetchJoke() {
      fetch("https://example-joke-api.com/random", {
        headers: {
          "api-key": "my-secret-key"
        }
      })
      .then(res => res.json())
      .then(data => {
        this.jokeData = data;
      })
      .catch(error => {
        console.error("Oops!", error);
      });
    }
  },
  created() {
    this.fetchJoke();
  }
}

This approach ensures that the API call is made when the component is created, and the joke data is properly updated in the component’s state. Hope this helps!

yo miat, i’ve been there too. ur fetch is outside the component, so Vue can’t react to changes. try movin it inside a method and call it in mounted() hook. like this:

methods: {
  getJoke() {
    fetch('url').then(res => res.json()).then(data => this.jokeData = data)
  }
},
mounted() {
  this.getJoke()
}

this shud work better. good luck!