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.
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:
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:
Move the fetch call into a method.
Call this method in the created() or mounted() lifecycle hook.
Use a data property to store the joke and update it when the fetch resolves.
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: