Skip to content

Commit

Permalink
complete suspense with a custom hook exercise
Browse files Browse the repository at this point in the history
  • Loading branch information
reysmerwvr committed Aug 19, 2023
1 parent 82d014a commit 1a8eff8
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 6 deletions.
61 changes: 61 additions & 0 deletions src/exercise/06.extra-1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Suspense with a custom hook
// http:https://localhost:3000/isolated/exercise/06.js

import * as React from 'react'
import {
PokemonInfoFallback,
PokemonForm,
PokemonDataView,
PokemonErrorBoundary,
usePokemonResource,
} from '../pokemon'

function PokemonInfo({pokemonResource}) {
const pokemon = pokemonResource.data.read()
return (
<div>
<div className="pokemon-info__img-wrapper">
<img src={pokemonResource.image.read()} alt={pokemon.name} />
</div>
<PokemonDataView pokemon={pokemon} />
</div>
)
}

function App() {
const [pokemonName, setPokemonName] = React.useState('')
const [pokemonResource, isPending] = usePokemonResource(pokemonName)

function handleSubmit(newPokemonName) {
setPokemonName(newPokemonName)
}

function handleReset() {
setPokemonName('')
}

return (
<div className="pokemon-info-app">
<PokemonForm pokemonName={pokemonName} onSubmit={handleSubmit} />
<hr />
<div className={`pokemon-info ${isPending ? 'pokemon-loading' : ''}`}>
{pokemonResource ? (
<PokemonErrorBoundary
onReset={handleReset}
resetKeys={[pokemonResource]}
>
<React.Suspense
fallback={<PokemonInfoFallback name={pokemonName} />}
>
<PokemonInfo pokemonResource={pokemonResource} />
</React.Suspense>
</PokemonErrorBoundary>
) : (
'Submit a pokemon'
)}
</div>
</div>
)
}

export default App
14 changes: 8 additions & 6 deletions src/exercise/06.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,10 @@ function createPokemonResource(pokemonName) {
return {data, image}
}

function App() {
const [pokemonName, setPokemonName] = React.useState('')
// 🐨 move these two lines to a custom hook called usePokemonResource
function usePokemonResource(pokemonName) {
const [startTransition, isPending] = React.useTransition(SUSPENSE_CONFIG)
const [pokemonResource, setPokemonResource] = React.useState(null)
// 🐨 call usePokemonResource with the pokemonName.
// It should return both the pokemonResource and isPending

// 🐨 move this useEffect call to your custom usePokemonResource hook
React.useEffect(() => {
if (!pokemonName) {
setPokemonResource(null)
Expand All @@ -67,6 +62,13 @@ function App() {
})
}, [pokemonName, startTransition])

return [pokemonResource, isPending]
}

function App() {
const [pokemonName, setPokemonName] = React.useState('')
const [pokemonResource, isPending] = usePokemonResource(pokemonName)

function handleSubmit(newPokemonName) {
setPokemonName(newPokemonName)
}
Expand Down

0 comments on commit 1a8eff8

Please sign in to comment.