Skip to content

Instantly share code, notes, and snippets.

@JayKan
Forked from kentcdodds/fetch-pokemon.js
Created December 25, 2018 00:01
Show Gist options
  • Select an option

  • Save JayKan/bc29c038da10143e5e41e79cbbbf1f12 to your computer and use it in GitHub Desktop.

Select an option

Save JayKan/bc29c038da10143e5e41e79cbbbf1f12 to your computer and use it in GitHub Desktop.
// 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