Last active
January 6, 2020 06:17
-
-
Save harrisonmalone/7c92eedc8dbd68d4ee87973b75e37ff3 to your computer and use it in GitHub Desktop.
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 from 'react'; | |
class App extends React.Component { | |
constructor(props) { | |
super(props) | |
// state definition | |
// data that belongs to a single component | |
this.state = { | |
count: 0, | |
message: '' | |
} | |
// 2, but it's a global variable available within this class that allows us to pause and unpause (clearInterval) | |
this.timerId = setInterval(this.setCount, 1000); | |
} | |
async componentDidUpdate(prevProps, prevState) { | |
const { count } = this.state | |
if (count % 2 === 0 && prevState.count !== this.state.count) { | |
const response = await fetch(`http://numbersapi.com/${count}/math`) | |
const message = await response.text() | |
this.setState({ | |
message: message | |
}) | |
} | |
} | |
setCount = async () => { | |
this.setState((prevState, prevProps) => { | |
return { count: prevState.count + 1 } | |
}) | |
} | |
pause = () => { | |
clearInterval(this.timerId) | |
} | |
unpause = () => { | |
this.timerId = setInterval(this.setCount, 1000); | |
} | |
reset = () => { | |
this.setState({ | |
count: 0 | |
}) | |
} | |
render() { | |
return ( | |
<> | |
<h1>count: {this.state.count}</h1> | |
<h3>message: {this.state.message}</h3> | |
<button onClick={this.reset} style={{ display: "block", padding: "20px", fontSize: "20px" }}>Reset</button> | |
<button onClick={this.pause} style={{ display: "block", padding: "20px", fontSize: "20px" }}>Pause</button> | |
<button onClick={this.unpause} style={{ display: "block", padding: "20px", fontSize: "20px" }}>UnPause</button> | |
</> | |
) | |
}; | |
} | |
export default App; | |
// todo | |
// 1. make the button to click on ✅ | |
// 2. give the button an onClick, event handler ✅ | |
// 3. use preventDefault to prevent refreshing ✅ | |
// 4. define a state, inside of the event handler we'll set some state ✅ | |
// 5. update render to display the counter ✅ | |
// 6. we need the counter to increment every second so we don't need to click anymore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment