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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With