Hi, do any of you know of a good solution or plug in to use when Axios is getting data from the database? Sometimes it can take a long time and then it would be good to display loader instead the component empty.
Just put an element when you start loading data (or, alternatively, keep it in DOM all the time and just show it), and then remove it (or hide) when it's done. I don't think you need a package for that.
@hjortur17 I usually just add a data entry for loading = true... then when my Axios call hits .then() I set it to false. This way you can apply classes, use v-if to hide sections or hold off loading the entire page based on that flag.
@fylzero Thanks. That worked great for me. I used the finally() to set loading to false, too.
But I want to show my loading spinner only if takes more than 1 second to axios response. I couldn't figure out a proper way to do it, tho.
@fylzero Yeah, I think it's safer to have this loading flag, instead of assuming that if data is empty when we are loading. There might be some edge cases where our data is still empty, but we already finished loading. That edge case could be some kind of unexpected error, for example.
I like using a "loading" flag as well for this, however I usually don't set it to false in the .then callback because if some kind of error occurs on the server side, I want to display the error, but also want to remove the loading indicator as well. To handle that, I use .finally.
axios.get('your.url')
.then(response => {
// populate data if returned
})
.catch(error => {
// handle the error
})
.finally(() => this.loading = false);
I think this might be more of a personal preference, but when I do this I know that regardless of the type of response I receive, the loading indicator will be removed.
@rawilk Thanks. That worked great for me. But I want to show my loading spinner only if takes more than 1 second to axios response. I couldn't figure out a proper way to do it, tho.
@heitor456 I would suggest you set a timeout for 1 second after which you then set loading to true. In the.finally() you could intercept the timeout and set loading to false. If fewen that 1 seconds pass, the loader won't have shown at all.
@topvillas That is possible but it would be a little aggressive. There is also a concept where you can program all your async/await calls to resolve all promises. If you could combine those concepts, maybe that would be cool.
I think it is probably best to deal with this on a case-by-case page-by-page basis though... since you may not always want it.
Kind of like how I used to have Bootstrap containers in my templates but now I put them in every page. Less DRY, but gives the option of having full-width marketing/admin panel pages, where wanted. That gives more granular control for each template and is more DRY than using separate layout blade files.