Best way to show a loading spinner/gif while my React component is fetching via AJAX?
The way I always solve this is for the component to track fetchInProgress
in its state.
Before you make your fetch, you set this value to true
; when the fetch completes (either success or fail), you set the value back to false
.
The component's render
method then honors this flag; if the flag is true
, it renders a spinner instead of a dataset.
var Foo = React.createClass({
handleButtonClick: function() {
// before making call, set fetch flag
self.setState({ fetchInProgress: true });
return $.ajax({
type: "POST",
url: "/some/refresh/url",
data: JSON.stringify({}),
dataType: "json",
contentType: "application/json",
success: (function(response) {
// when updating with dataset, also reset fetch flag
self.setState({
fetchInProgress: false,
myList: response.list
});
}),
failure: ((function(reason) {
// make sure to reset even if fetch fails!
self.setState({
fetchInProgress: false
});
})
});
},
render: function() {
return (
<div className="container">
<ul>
{
this.state.fetchInProgress
: <Spinner />
: this.state.myList.map(function(item) {
return <li id="{item.id}">{item.name}</li>
})
}
</ul>
<input type="submit" value="REFRESH LIST" onClick={this.handleButtonClick} />
</div>
);
}
});
React - Display loading screen while DOM is rendering?
This could be done by placing the loading icon in your html file (index.html
for example), so that users see the icon immediately after the html file has been loaded.
When your app finishes loading, you could simply remove that loading icon in a lifecycle hook, I usually do that in componentDidMount
.
Show loading image while $.ajax is performed
You can, of course, show it before making the request, and hide it after it completes:
$('#loading-image').show();
$.ajax({
url: uri,
cache: false,
success: function(html){
$('.info').append(html);
},
complete: function(){
$('#loading-image').hide();
}
});
I usually prefer the more general solution of binding it to the global ajaxStart and ajaxStop events, that way it shows up for all ajax events:
$('#loading-image').bind('ajaxStart', function(){
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});
How to make React loading indicator show after waiting short interval?
You can do a little hack there. Maintain a component state, which keep track of, if the timer is over or not something like this:
componentWillReceiveProps(newProps){
if(newProps.ajaxCallsInProgress > 0 && !this.state.timerOver){
setTimeout(() => { this.setState({timerOver: true});}, 200)
}
else if(newProps.ajaxCallsInProgress <= 0){
this.setState({timerOver: false});
}
}
render(){
return(
<Spinner show={this.props.ajaxCallsInProgress > 0 && this.state.timerOver} />
)
}
What is the best way to show ajax loading image above the existing image?
I use spin.js, wrapped in this little jquery plugin.
So I just do:
$el = $("#el"); // cache element fo further reference
$el.spin(); // put spinner in the middle of selected element.
// do your stuff...
$el.spin(false); // dismiss spinner.
See it live here.
How to show loading spinner in jQuery?
There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.
$('#loadingDiv')
.hide() // Hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
The ajaxStart/Stop functions will fire whenever you do any Ajax calls.
Update: As of jQuery 1.8, the documentation states that .ajaxStart/Stop
should only be attached to document
. This would transform the above snippet to:
var $loading = $('#loadingDiv').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
How to add a loading animation while Fetch data from API? Vanilla js
add loader before call and remove once you receive results, as follows
const movieApiMovies = () => {
let loader = `<div class="boxLoading"></div>`;
document.getElementById('movieResult').innerHTML = loader;
fetch(movieApi_url + "movies/")
.then(response => response.json())
.then(function (data) {
let result = `<h2> Movies I've watched! </h2>`;
data.forEach((movie) => {
const {id, name, year, note_imdb, genre, duration} = movie;
result +=
`<div>
<h5> Movie ID: ${id} </h5>
<ul>
<li>Movie name: ${name}</li>
<li>Movie year: ${year}</li>
<li>Movie note on IMDB: ${note_imdb}</li>
<li>Movie Genre: ${genre}</li>
<li>Movie duration: ${duration}</li>
</ul>
</div>`;
document.getElementById('movieResult').innerHTML = result;
})
})
};
Related Topics
Javascript Backslash (\) in Variables Is Causing an Error
How to Get the Index from a Json Object With Value
Javascript Restrict Text Field to Numbers and Decimals
Javascript Generate Random Numbers Without Repeating
How to Reload Datatable by Ajax (Jquery)
Array Push Is Overwriting the Existing Array
Make Redirect to New Url But Remove Previous from History
How to Add a Simple Onclick Event Handler to a Canvas Element
Simple Pagination in JavaScript
Javascript to Download a File from Amazon S3 Bucket
Calculate and Display % Discount for Price Classes JavaScript
How to Refresh Select Option List After Ajax Response
Javascript Submit Multiple Forms With One Button
How to Prevent Invalid Characters from Being Typed into Input Fields
Merge Array of Objects by Same Key-Value
Text Box to Appear When a Radio Button Is Selected
Call External JavaScript Function from React Typescript Components