We can make an HTTP request on page load by using the lifecycle method created()
. The created()
hook basically gets called when the components get created. The data properties are set up before the created()
hook is called, making it a better option to make an external API request to initialize data properties.
In this article, we will look at how to make an HTTP request when a page is loaded in Vue using created()
lifecycle method.
We will begin by creating a new application using Vue CLI.
❯ vue create created-demo
Once, the installation is complete, we can navigate to the folder and run the server to load the application.
❯ cd created-demo
❯ npm run serve
This will run our server on port 8080 by default http://localhost:8080/
Created() lifecycle method
Let’s begin by defining a method that will make an HTTP request to fetch data. In our example, we will make use of the Meme generator API called Imgflip API.
We will be making use of the fetch()
to call the API. Fetch is a web API used for making HTTP requests from the client side.
getMemes() {
fetch("https://api.imgflip.com/get_memes")
.then((response) => response.json())
.then((json) => {
console.log(json);
});
}
The getMemes()
method fetches the first 10 memes from the API which we will display on our page.
We will also have a data property memes
that will be an empty array initially.
data() {
return {
memes: [],
};
}
Now, we can make use of the memes
property in the getMemes()
method.
getMemes() {
fetch("https://api.imgflip.com/get_memes")
.then((response) => response.json())
.then((json) => {
this.memes = json.data.memes.slice(0, 10);
});
}
But we want to ensure that this method gets called when the page gets loaded. To make this happen, we will call it from within the created()
hook as follows:
created() {
this.getMemes();
}
Once the component gets created, the created()
method gets called which will then call the getMemes()
method to populate the data from the API.
Let’s make changes to the App.vue
file to see the above code in action.
// App.vue
<template>
<div v-if="memes.length">
<div v-for="meme in memes" :key="meme.id">
<h2>{{ meme.name }}</h2>
<img :src="meme.url" width="100" />
</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
memes: [],
};
},
methods: {
getMemes() {
fetch("https://api.imgflip.com/get_memes")
.then((response) => response.json())
.then((json) => {
this.memes = json.data.memes.slice(0, 10);
});
},
},
created() {
this.getMemes();
},
};
</script>
The output:
This way the data from the API gets fetched as soon as the page gets loaded.