Last active
August 28, 2020 04:19
-
-
Save joshamore/82513887274dd4559bebca6a86206e6a to your computer and use it in GitHub Desktop.
Fetching data after page render with React Hooks
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, { 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