I’m working on a Vue.js project and trying to fetch data from RapidAPI but having trouble displaying it properly. The API call seems to work but the data doesn’t show up in my template. Instead I just see the initial empty array value.
<template>
<div>
<div>{{ movieInfo }}</div>
</div>
</template>
<script>
var movies = [];
fetch("https://example-movie-api.p.rapidapi.com/films/popular", {
method: "GET",
headers: {
"x-rapidapi-host": "example-movie-api.p.rapidapi.com",
"x-rapidapi-key": "***"
}
})
.then(response => response.json())
.then(result => {
movies = result;
})
.catch(error => {
console.log(error);
});
export default {
data() {
return {
movieInfo: movies
};
}
};
</script>
I also attempted this approach:
var movies fetch("https://example-movie-api.p.rapidapi.com/films/popular", {...}
But that just gives me [object Promise] instead of the actual data I need to display. What’s the correct way to handle this?
Your fetch call runs outside Vue’s lifecycle, so the data isn’t reactive. Move the API call into a lifecycle hook and bind the response to your component’s data properly. Here’s what worked for me:
export default {
data() {
return {
movieInfo: []
};
},
async mounted() {
try {
const response = await fetch("https://example-movie-api.p.rapidapi.com/films/popular", {
method: "GET",
headers: {
"x-rapidapi-host": "example-movie-api.p.rapidapi.com",
"x-rapidapi-key": "***"
}
});
const result = await response.json();
this.movieInfo = result;
} catch (error) {
console.log(error);
}
}
};
The key is using this.movieInfo = result
inside the mounted hook - this way Vue’s reactivity system tracks changes and updates your template.
Your fetch call runs before Vue initializes the component, so the API response never hits your reactive data. I’ve hit this same issue when working with external APIs in Vue. Move your fetch logic inside the component and update the reactive data property directly. Don’t declare movies as a global variable - handle everything within Vue’s component lifecycle. You can also use created() if you want the data loading earlier than mounted(). Just make sure you’re using this.movieInfo when assigning the API response, or Vue won’t detect the change and your template won’t update.
yeah, you should run the fetch call inside mounted(). make sure to set this.movieInfo = result so your component updates correctly. also, initialize movieInfo as an empty array in data() instead of using the movies var.