Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - Which component lifecycle should be used for fetching data?

After reading one of Alligator.io posts about Vue that was saying that mounted lifecycle is a bad place to use http get. I was wondering if there are any guidelines to how properly get data from API in Vue.js?

like image 592
kkot Avatar asked Jul 27 '18 08:07

kkot


People also ask

What is the life cycle of Vue component?

Each Vue component instance goes through a series of initialization steps when it's created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes.

Which Vue lifecycle hook is a good place to perform any cleanup for a component?

Destruction hooks allow you to perform actions when your component is destroyed, such as cleanup or analytics sending. They fire when your component is being torn down and removed from the DOM.

What is life cycle hook in Vue?

Lifecycle hooks are pre-defined methods that get executed in a certain order, starting from the initialization of the Vue instance to its destruction. Below is a diagram that indicates the Vue JS lifecycle hooks sequence. There are eight lifecycle hooks in Vue JS: beforeCreate. created.

What is fetch in Vue?

JavaScript Fetch API provides an interface for accessing and manipulating HTTP requests and responses. In this Vuejs tutorial, we will create Vue Fetch example to make Get/Post/Put/Delete request with Rest API and JSON data.


2 Answers

I`m prefer call API in created hook. Quote from alligator.io:

In the created hook, you will be able to access reactive data and events are active. Templates and Virtual DOM have not yet been mounted or rendered.

So you easy can access to data to parse and save response from a server if you need.

Regards.

like image 125
wkornilow Avatar answered Oct 26 '22 11:10

wkornilow


The created() lifecycle hooks fullfills all requirements for fetching and processing API data.

However the official Vue documentation uses the mounted() lifecycle hook in example code for integration API calls with axios: https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html

Both lifecycle hooks mounted() and created() are widely used for fetching API data and considered as good practice.

like image 34
Simon Thiel Avatar answered Oct 26 '22 13:10

Simon Thiel