Created
January 16, 2018 22:57
-
-
Save pkellner/a7c4a3231453c73c27a5e6f76973be0d to your computer and use it in GitHub Desktop.
React Component To Show Loading a Waiting Message Only When Necessary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component} from 'react'; | |
import axios from 'axios'; | |
class App extends Component { | |
constructor() { | |
super(); | |
this.timeIncrementMs = 50; | |
this.showSpinnerIfReturnGreaterThanMs = 200; | |
this.state = { | |
isLoading: true, | |
msElapsed: 0 | |
}; | |
} | |
componentWillUnmount() { | |
clearInterval(this.incrementer); | |
} | |
componentWillMount() { | |
this.incrementer = setInterval(() => | |
this.setState({ | |
msElapsed: this.state.msElapsed + this.timeIncrementMs | |
}) | |
, this.timeIncrementMs); | |
axios.get("https://api.github.com/users/pkellner/repos") | |
.then((result) => { | |
this.setState({ | |
appData: result.data, | |
isLoading: false | |
}); | |
}) | |
.catch(error => { | |
if (error.response) { | |
console.log(error.responderEnd); | |
} | |
}); | |
} | |
render() { | |
if (this.state.isLoading && | |
this.state.msElapsed > this.showSpinnerIfReturnGreaterThanMs) { | |
return <h1>LOADING</h1>; | |
} else if (this.state.isLoading && | |
this.state.msElapsed <= this.showSpinnerIfReturnGreaterThanMs) { | |
return (null); | |
} | |
const content = this.state.appData.map((repo) => | |
<li key={repo.id}> | |
{repo.name} | |
</li>); | |
return ( | |
<ul> | |
{content} | |
</ul> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment