Last active
February 27, 2019 11:41
-
-
Save j-mes/b326a104c5d553324a971297e741c4c0 to your computer and use it in GitHub Desktop.
React Class vs Hooks for fetching from an API
This file contains 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
// Using React Class for fetching from an API | |
class Test extends React.Component { | |
constructor(...args) { | |
super(...args); | |
this.state = undefined; | |
} | |
componentDidMount() { | |
fetch('/api/endpoint') | |
.then(res => res.json()) | |
.then(json => this.setState(json)); | |
} | |
render() { | |
return this.state ? <pre>{JSON.stringify(this.state)}</pre> : null; | |
} | |
} | |
// Using React Hook for fetching from an API | |
const Test = () => { | |
const [state, update] = React.useState(undefined); | |
React.useEffect(() => { | |
fetch('/api/endpoint') | |
.then(res => res.json()) | |
.then(json => update(json)); | |
}); | |
return state ? <pre>{JSON.stringify(state)}</pre> : null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment