I’m looking for help with displaying data from an API in my Vue application
I’m currently building a Vue application, and I want to retrieve data from RapidAPI to show it on my page. However, I’m facing an issue where my component only displays an empty array instead of the actual API results.
The rendered page simply shows [], which is the default value I initialized. I also attempted a different method where I directly assigned the fetch response, but it resulted in [object Promise] rather than the expected data.
What is the correct approach to fetch and display this API data in my template?
This happens because your fetch runs outside Vue’s lifecycle. When the component loads, apiResults is still empty since the API call hasn’t finished yet. You need to move that fetch logic inside the mounted() hook and assign the response directly to this.apiData instead of using an external variable. Also throw in a loading state to handle the gap between when the component mounts and when your data actually shows up.
The problem is your fetch runs when the script loads, but Vue needs reactive data updates. You’re treating apiResults like a static variable that gets set once outside Vue’s reactivity system. Fix this by initializing apiData as an empty array in your data function. Then use created() or mounted() to make the API call. In your .then() block, assign the response directly to this.apiData instead of an external variable. Vue will detect the change and re-render automatically. You should also add error handling in your catch block and maybe throw in a loading indicator since API calls take time.
hey, i get it. the fetch is async, so the data isn’t available when the component renders. try moving the fetch to the mounted() lifecycle hook and set this.apiData directly. that should fix the empty array issue!