I recently came across an article on Alligator.io discussing the drawbacks of using the mounted lifecycle in Vue for HTTP requests. This got me thinking, are there any best practices or guidelines for fetching data from APIs in Vue.js?
I recently came across an article on Alligator.io discussing the drawbacks of using the mounted lifecycle in Vue for HTTP requests. This got me thinking, are there any best practices or guidelines for fetching data from APIs in Vue.js?
I personally like to call APIs in the created hook. As mentioned on alligator.io:
When using the created hook, you can access reactive data and active events. Templates and Virtual DOM elements have not been mounted or rendered yet.
This makes it easy to access data for parsing and saving server responses if needed.
The created()
lifecycle method effectively handles the fetching and processing of API data.
Interestingly, the official Vue documentation showcases the use of the mounted()
lifecycle hook in their code examples for integrating API calls with axios:
https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html
Both mounted()
and created()
lifecycle hooks are commonly utilized for retrieving API data and are recognized as best practices in Vue development.
The solutions provided are logical, however if we utilize the mounted()
hook to access the APIs, assuming that the DOM has been rendered. If we modify a state within mounted()
, will it prompt another rendering?
I am convinced that in the created()
hook, the DOM is not yet initialized. Therefore, I am inclined towards utilizing the created()
hook.
Solution:
The optimal hooks to use in this scenario are mounted
and beforeMounted
, although there may be exceptions.
Reasoning:
created
hook does not guarantee that Vue will apply it upon the next mount. This can lead to situations where a component's state is saved, even if it is not immediately visible.created
hook as this may cause errors during rendering. The mounted hook only functions on the client side.If you are concerned about performance or timing, consider that fetch operations will occur after both the created
and mounted
hooks, as they are asynchronous whereas hooks are synchronous. Additionally, the time lapse between created
and beforeMounted
is minimal.
If SSR is not a concern and you have a strong understanding of Vue's workings, placing fetch methods in the created
hook may be appropriate for your specific needs.
According to the Vue official documentation, it is recommended to fetch data in the created
hook. You can find more information about this here: https://router.vuejs.org/guide/advanced/data-fetching.html
However,
The decision of when and where to fetch data depends on various factors such as the type of data, its significance, and the limitations of the user's device (which can impact rendering performance due to heavy browser computations).
If the data is crucial and needs to be displayed immediately, fetching it in the created
hook is advisable. On the other hand, if the data is not time-sensitive, performing the fetch operation or any other intensive calculations in the created
hook may lead to render blocking or jank issues (resulting in delayed DOM rendering). This is especially true for users on mobile devices or with limited resources like low memory or weak processors.
Is it feasible to use Ajax for posting a form containing text and images through an HTML form, and receiving the response back via Ajax? Steps 1.) Include the form in HTML with a submit button. 2.) Submit the form to PHP, where it will process and upload ...
I've been struggling to get the latest Superfish menu code working with lists that include the <a> tag. I've double-checked everything, but it seems like I'm missing something obvious. Can anyone help me figure out what's wrong? ...
With the latest version of Vue SFC (3.3+), slot scope has become type safe with the introduction of defineSlots. Is there a way to achieve the same type safety for slots in functional components as well? export default defineComponent({ name: 'MyCompo ...
In my current project, I am utilizing Laravel but it is not a Vue Single Page Application (SPA) so no routes are being used. Instead, the registration, login, and other form interactions are done through modals using Vue. Axios is being used to send form ...
I'm currently working on placing multiple images on a grid in the center of the page and would like to include a function that triggers when each individual image is clicked. The images are dynamically created using JavaScript and inserted into the do ...
I am looking to capitalize the input data from the user's full name model and would prefer if it is in Latin letters only. Utilizing Vue.js for Uppercase Conversion <p-input :value="value" @input="$emit('input', $event)&qu ...
Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...
I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...
My goal is to extract all characters that come after the equal sign within a URL: let url = this.$route.query.item console.log(typeof(url)) // outputs string let status = url => url.split('=')[1] When I run the code, it shows &apo ...
Could anyone help me with drawing a rectangle using React? I'm having trouble getting it to work. I'm confused as to why the code below isn't showing a rectangle on the screen. class DrawingView{ constructor(props) { this.canva ...
Currently, I am working on a front-end project using [THIS VUE TEMPLATE][https://www.creative-tim.com/product/vue-material-dashboard-pro] The issue I am facing involves trying to register a component locally and encountering the following error: "1 ...
I am attempting to implement a delete function using Ajax. function delCatItem(catitem){ var theitem = catitem; $.ajax({ url: "movie/deleteitem/", type: "POST", data: { "movieid" : catitem ...
I am grappling with the optimal structure for a React component that is composed of other components. Let's look at the first example: <ColorSelect id="color" label={this.state.selectLabel} trigger={{ color: "lime", text: "Lime"}} onPropagateCli ...
In my current script, I am loading external content using the following code: <script type="text/javascript"> var http_request = false; function makePOSTRequest(url, parameters) { // Code for making POST request } function alertContents() { ...
My journey with Material UI version 5 has just begun. In the past, I would utilize makestyles to incorporate my custom theme's styles; however, it appears that this method no longer works in v.5. Instead of relying on {createMuiTheme}, I have shifted ...
I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...
I've been struggling to understand how to effectively write AngularJS directives, even after reading various blogs. The issue I am facing is with an array of names in the format "lastname, firstname". My goal is to create a directive that will display ...
I am having trouble comparing strings in this array. For some reason, the strings are never equal. var person = ["Sam", "John", "Mary", "Liz"]; var searchedName = prompt("Enter name"); var resultMessage = ""; for (index in person) { var currentName = ...
When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...
What is the best method to extract information from the array below? How can I retrieve data categorized by specific categories? Is there a way to access only the key values? How do I retrieve just the data values? var main = [{ "key": "all", "dat ...