Created
July 29, 2022 16:11
-
-
Save with-heart/ee79c54914e0fd759b87c4df7f5ff676 to your computer and use it in GitHub Desktop.
react async fetching
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
import { useEffect, useState } from 'react' | |
export const Component = () => { | |
const [whatevers, setWhatevers] = useState([]) | |
const [isLoading, setIsLoading] = useState(false) | |
const [error, setError] = useState() | |
useEffect(() => { | |
const loadWhatevers = async () => { | |
// show loading status | |
setLoading(true) | |
try { | |
// let's try to fetch our data | |
const response = await fetch('https://some-url.com') | |
const data = await response.json() | |
// now that we have data, let's store it! | |
setWhatevers(data) | |
} catch (error) { | |
// fetch failed, so we'll store the error | |
setError(error) | |
} finally { | |
// regardless of success or error, | |
// we need to stop loading | |
setLoading(false) | |
} | |
} | |
// let's get to loadin' yall | |
loadWhatevers() | |
// since the dependency array is empty, we'll only | |
// run this effect once. if we wanted to run it again | |
// (like if the fetch depends on the value of a prop | |
// or we want to let the user retry on error), we'd | |
// need to add a variable in there to sync the effect with | |
}, []) | |
return ( | |
<div> | |
<h1>Whatevers</h1> | |
{isLoading && <p>Loading...</p>} | |
{error && <p>Error: {error}</p>} | |
{whatevers.map(whatever => ( | |
// render the whatever here | |
)} | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment