forked from epicweb-dev/react-suspense
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9fdf1c1
commit 2b0f245
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
// Simple Data-fetching | ||
// http://localhost:3000/isolated/exercise/01.js | ||
|
||
import * as React from 'react' | ||
import {fetchPokemon, PokemonDataView, PokemonErrorBoundary} from '../pokemon' | ||
|
||
|
||
function createResource(promise) { | ||
let status = 'pending' | ||
let result = promise.then( | ||
resolved => { | ||
status = 'success' | ||
result = resolved | ||
}, | ||
rejected => { | ||
status = 'error' | ||
result = rejected | ||
}, | ||
) | ||
|
||
return { | ||
read() { | ||
if (status === 'pending') throw result | ||
if (status === 'error') throw result | ||
if (status === 'success') return result | ||
throw new Error('Unable to fetch pokemon') | ||
}, | ||
} | ||
} | ||
|
||
let pokemonResource = createResource(fetchPokemon('pikachu')) | ||
|
||
function PokemonInfo() { | ||
const pokemon = pokemonResource.read() | ||
return ( | ||
<div> | ||
<div className="pokemon-info__img-wrapper"> | ||
<img src={pokemon.image} alt={pokemon.name} /> | ||
</div> | ||
<PokemonDataView pokemon={pokemon} /> | ||
</div> | ||
) | ||
} | ||
|
||
function LoadingPokemon() { | ||
return <div>loading pokemon...</div> | ||
} | ||
|
||
function App() { | ||
return ( | ||
<div className="pokemon-info-app"> | ||
<div className="pokemon-info"> | ||
<PokemonErrorBoundary> | ||
<React.Suspense fallback={<LoadingPokemon />}> | ||
<PokemonInfo /> | ||
</React.Suspense> | ||
</PokemonErrorBoundary> | ||
</div> | ||
</div> | ||
) | ||
} | ||
|
||
export default App |