Skip to content

Instantly share code, notes, and snippets.

@j-mes
Last active February 27, 2019 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j-mes/b326a104c5d553324a971297e741c4c0 to your computer and use it in GitHub Desktop.
Save j-mes/b326a104c5d553324a971297e741c4c0 to your computer and use it in GitHub Desktop.
React Class vs Hooks for fetching from an API
// 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