Last active
February 6, 2022 05:29
-
-
Save kentcdodds/2510249a3fc5c9dce82ccee80396fc6a to your computer and use it in GitHub Desktop.
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
// NOTE: you will NOT write code like this when using suspense | |
// instead, you'll use react-cache (not yet officially published) | |
// it'll handle things like pre-loading, handling rapid re-renders, etc. | |
const cache = {} | |
function FetchPokemon({pokemonName}) { | |
const pokemon = cache[pokemonName] | |
if (!pokemon) { | |
const promise = fetchPokemon(pokemonName).then( | |
pokemon => (cache[pokemonName] = pokemon), | |
) | |
// the placeholder will catch this and | |
// rerender when the promise resolves | |
throw promise | |
} | |
return <pre>{JSON.stringify(pokemon || 'Unknown', null, 2)}</pre> | |
} | |
function PokemonInfo({pokemonName}) { | |
return ( | |
<React.Placeholder fallback="loading pokemon data..."> | |
<FetchPokemon pokemonName={pokemonName} /> | |
</React.Placeholder> | |
) | |
} | |
// Usage: <PokemonInfo pokemonName="Pikachu" /> | |
// Cool right? These are all function components! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment