The main issue I have found using the setting manually a "loading" flag to
true / false is that is quite easy to skip by mistake the set to false flag and your application would like hanged), and on the other hand I dont' want to mess up when several ajax request are being called in parallel, this comes even more harder when you want to track some of them, but in other cases you want to make silent requests.
I have created a microlibrary called react-promise-tracker to handle this in a more automatic way. How it works
Install promise tracker
npm install react-promise-tracker --save
Implement a simple loading indicator component (you can add the style you need for it), and wrap it with the promiseTrackerHoc
import { promiseTrackerHoc } from 'react-promise-tracker';
const InnerLoadingIndicator = props => (
props.trackedPromiseInProgress &&
<h1>Hey some async call in progress ! Add your styling here</h1>
);
export const LoadingIndicator = promiseTrackerHoc(InnerLoadingIndicator);
Instantiate it in your application root component:
render(
<div>
<App />
<LoadingIndicator/>
</div>,
document.getElementById("root")
);
Whenever you want to track a fetch or any promise based call (including async/await), just wrap it with the react-promise-tracker function trackPromise:
import { trackPromise } from 'react-promise-tracker';
export class MyComponent extends Component {
componentWillMount() {
trackPromise(
userAPI.fetchUsers()
.then((users) => {
this.setState({
users,
})
})
);
}
// ...
}
More resources:
- Step by step tutorial (including adding a nice looking spinner): https://www.basefactor.com/react-how-to-display-a-loading-indicator-on-fetch-calls
fetch
requests, and you don't want to intercept them. Or you might want to migrate away from intercepting all your own requests. To increase maintainability, just write your own wrapper function that does handle the spinner, and then call it whereever you need to do a request with a spinner. – Bergi May 6 '17 at 10:11