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.
I have been using the div tag to create a line, but I'm looking for an easier solution. If you have another method in mind, please share it with me. #line{ background-color:black; height:1px; width:50px; margin-top:50px; margin-left:50px; f ...
Currently, I am in the process of creating a bookmarklet that will require some user details to be input. After researching my options for cross domain communication, I have found that my best choices are either using jQuery.getJSON or adding a form and i ...
My response to a question about closures on SO included the following code sample: function Constructor() { var privateProperty = 'private'; var privateMethod = function(){ alert('called from public method'); }; ...
I recently started working with Next.js and have developed an application using it. On the homepage, I have a timer set for 10 seconds. When the timer hits 0, I want to redirect the user to a feedback page in my "pages" folder. Below is the code I am usin ...
Sometimes, I find myself needing to handle arrays and single objects in a similar manner. For instance, I may have an object property that can be either an array or just a string (like the scale property): [ { "name": "Experiment type14", "id": ...
For a beginner in javascript and jquery like me, I encountered an issue with a textarea element that has preset content. When I change the value on the site to "new" and click the "showme" button, the alert box displays the preset value instead of the new ...
My application development journey began with cloning code from https://github.com/DMPRoadmap/roadmap. This project is based on webpack and npm. To integrate select2, I executed npm install select 2 in the lib/assets directory. I aimed to incorporate a ...
Hi everyone, I'm a beginner in javascript and I am currently working on finding the download time of a file. I have calculated the size of the file and divided it by the current time, but unfortunately, I am not getting the correct result. This is th ...
I am currently following a tutorial on Vue.js from Savvy Apps, which utilizes Firebase with Firestore. As the tutorial mentions that Firestore is still in Beta, I anticipate potential changes - and it seems like that might be happening in this case. While ...
Currently, I am utilizing Ajax to retrieve data from my Json file. A problem I am facing is that in one particular div of my html, I need to include both a heading and a paragraph. I attempted to create a property like so: "headingpara": "<h1> blah ...
Recently, I have been following a tutorial/example from codeschool and everything is going well. However, the example code includes the line: App.ApplicationAdapter = DS.FixtureAdapter.extend(); Now, I want to maintain all the existing functionality but ...
Working on a Connect Four app for my school project has been an interesting challenge. At the moment, I am grappling with JSON.stringify and trying to encode an object that holds a two-dimensional array of "hole" objects to eventually send it to the server ...
I have a spreadsheet where column 1 contains source file IDs, with each cell holding only one ID. Column 2 has destination file IDs, where cells contain multiple IDs separated by commas. I utilize a script to retrieve these values and perform various opera ...
Below is an array that contains comments, and I am attempting to display them in a threaded manner by utilizing the parentId property. comments: [ { id: 1, parentId: null }, { id: 2, parentId: 1 }, { id: 3 ...
When I expect the image to return mirrored, it instead shows up as a black image. <!DOCTYPE html> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <bo ...
Below is some Vue.js code that I've been working on. When accessing the URL directly in my browser, the data (in JSON format) is retrieved without any issues. However, when trying to retrieve this data through an HTTP request, it doesn't seem to ...
Looking to connect two divs with a straight line, I stumbled upon jQuery DOM line, which appears to offer a more streamlined solution compared to jsPlump. I attempted to incorporate it into my code, but unfortunately, it's not working as expected. Be ...
I'm new to ajax and recently encountered an issue while working on a project where I needed to send a query from an HTML form. However, I've been unable to send any data for some reason. I tried sending FormData through the xmlhttprequest.send() ...
Imagine I have a vuejs component named child-component that is inserted into a parent component in the following manner. <child-component> <div>Hello</div> </child-component> Please note, this does not represent the template of ...
As I work on my website, I encountered an issue with a div containing a table. The div expands to full width, but when I resize the screen, it shrinks causing the content to overlap. I am looking for a solution where the minimum width of the div adjusts b ...