Skip to content

Instantly share code, notes, and snippets.

@joshamore
Last active August 28, 2020 04:19
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 joshamore/82513887274dd4559bebca6a86206e6a to your computer and use it in GitHub Desktop.
Save joshamore/82513887274dd4559bebca6a86206e6a to your computer and use it in GitHub Desktop.
Fetching data after page render with React Hooks
import React, { useEffect } from "react";
function App() {
// Setting up the useEffect hook
// This will trigger on the first reload of the page thanks to the empty []
useEffect(() => {
// Fetching data
fetch("https://jsonplaceholder.typicode.com/todos/1")
// Converting response to a useable JSON format
.then((response) => response.json())
// Doing something with the returned data
.then((json) => {
// Prining returned data to the console once it's received
// This is where you might update a state item to cause a rerender with the returned data
console.log(json);
})
// If there's an error with the fetch, prining to console
.catch((err) => console.log(err));
}, []);
return (
<div className="App">
<h1>This is an example</h1>
<p>
Check your devtools console. You should see an object arriving after the
page renders.
</p>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment