Reputation: 89
So this is more or less the code
Sorry for the syntax, I typed it from my phone
export default class Main extends React.Component {
componentDidMount() {
axios.get('/user?ID=12345')
.then(function (response) {
if (response){
document.addEventListener('load', () => {/* remove spinner using jquery */});
} else { /* redirect to somewhere else */}
})
}
render() {
return (
<SomeComponent />
);
}
}
I used addEventListener with React because I couldn't find any other way to bind the removal of the loading spinner to the load event.
The issue is that there is a race here, for slow network stations or fast CPUs ones, the load event may be launched long before the request is resolved, which results in the loading spinner to remain.
Is there maybe a way to check if the load event was already lanched?
If I can do that, I'll be able to check it after adding the event listener and in case it was already launched, I'll remove the spinner manually.
Upvotes: 0
Views: 733
Reputation: 31024
I would't use jquery for this task (or at all in react) as you can do it in a more "reactish" way.
You can store the data in your state
and conditionally render the component in your render
method when the state has changed.
You can't avoid the first render
by the way.
Small example:
const Loader = () => <div>Loading...</div>
const MyComponent = ({message}) => <div>{message}</div>
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: ''
};
}
componentDidMount(){
// mimic async operation
setTimeout(()=>{
this.setState({message: 'Hi there!'})
}, 1500);
}
render() {
const {message} = this.state;
return (
<div>
{message ? <MyComponent message={message} /> : <Loader />}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Edit
As a followup to your comment:
But then you re-render the entire component just to change the display style of the preloader element, right?
Not entirely true i think you should read more about Reconciliation and The Diffing Algorithm and look at this example:
React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.
Upvotes: 3