-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add useSuspendAll hook & react/suspense example
- Loading branch information
1 parent
f098c92
commit 7ef04e5
Showing
25 changed files
with
1,285 additions
and
20 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
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 @@ | ||
SKIP_PREFLIGHT_CHECK=true |
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,43 @@ | ||
{ | ||
"name": "@examples-query-react/suspense", | ||
"private": true, | ||
"version": "1.0.0", | ||
"description": "", | ||
"keywords": [], | ||
"main": "src/index.tsx", | ||
"dependencies": { | ||
"@reduxjs/toolkit": "^1.8.0", | ||
"clsx": "^1.1.1", | ||
"react": "17.0.0", | ||
"react-dom": "17.0.0", | ||
"react-error-boundary": "3.1.4", | ||
"react-redux": "7.2.2", | ||
"react-scripts": "4.0.2", | ||
"use-sync-external-store": "^1.0.0" | ||
}, | ||
"devDependencies": { | ||
"@types/react": "17.0.0", | ||
"@types/react-dom": "17.0.0", | ||
"@types/react-redux": "7.1.9", | ||
"@types/use-sync-external-store": "^0.0.3", | ||
"typescript": "~4.2.4" | ||
}, | ||
"eslintConfig": { | ||
"extends": [ | ||
"react-app" | ||
], | ||
"rules": { | ||
"react/react-in-jsx-scope": "off" | ||
} | ||
}, | ||
"scripts": { | ||
"start": "react-scripts start", | ||
"build": "react-scripts build" | ||
}, | ||
"browserslist": [ | ||
">0.2%", | ||
"not dead", | ||
"not ie <= 11", | ||
"not op_mini all" | ||
] | ||
} |
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,42 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="utf-8" /> | ||
<meta | ||
name="viewport" | ||
content="width=device-width, initial-scale=1, shrink-to-fit=no" | ||
/> | ||
<meta name="theme-color" content="#000000" /> | ||
<!-- | ||
manifest.json provides metadata used when your web app is added to the | ||
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/ | ||
--> | ||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> | ||
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" /> | ||
<!-- | ||
Notice the use of %PUBLIC_URL% in the tags above. | ||
It will be replaced with the URL of the `public` folder during the build. | ||
Only files inside the `public` folder can be referenced from the HTML. | ||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will | ||
work correctly both with client-side routing and a non-root public URL. | ||
Learn how to configure a non-root public URL by running `npm run build`. | ||
--> | ||
<title>React App</title> | ||
</head> | ||
|
||
<body> | ||
<noscript> You need to enable JavaScript to run this app. </noscript> | ||
<div id="root"></div> | ||
<!-- | ||
This HTML file is a template. | ||
If you open it directly in the browser, you will see an empty page. | ||
You can add webfonts, meta tags, or analytics to this file. | ||
The build step will place the bundled scripts into the <body> tag. | ||
To begin the development, run `npm start` or `yarn start`. | ||
To create a production bundle, use `npm run build` or `yarn build`. | ||
--> | ||
</body> | ||
</html> |
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,8 @@ | ||
{ | ||
"short_name": "RTK Query Polling Example", | ||
"name": "Polling Example", | ||
"start_url": ".", | ||
"display": "standalone", | ||
"theme_color": "#000000", | ||
"background_color": "#ffffff" | ||
} |
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,45 @@ | ||
import * as React from 'react' | ||
import { POKEMON_NAMES } from './pokemon.data' | ||
import './styles.css' | ||
import { PokemonSingleQueries } from './PokemonSingleQueries' | ||
import { PokemonParallelQueries } from './PokemonParallelQueries' | ||
|
||
const getRandomPokemonName = () => | ||
POKEMON_NAMES[Math.floor(Math.random() * POKEMON_NAMES.length)] | ||
|
||
export default function App() { | ||
const [errorRate, setErrorRate] = React.useState<number>( | ||
window.fetchFnErrorRate | ||
) | ||
|
||
React.useEffect(() => { | ||
window.fetchFnErrorRate = errorRate | ||
}, [errorRate]) | ||
|
||
return ( | ||
<div className="App"> | ||
<div> | ||
<form action="#" className="global-controls"> | ||
<label htmlFor="error-rate-input"> | ||
fetch error rate: {errorRate} | ||
<input | ||
type="range" | ||
name="erro-rate" | ||
id="error-rate-input" | ||
min="0" | ||
max="1" | ||
step="0.1" | ||
value={errorRate} | ||
onChange={(evt) => { | ||
setErrorRate(Number(evt.currentTarget.value)) | ||
}} | ||
/> | ||
</label> | ||
</form> | ||
</div> | ||
<PokemonParallelQueries /> | ||
<hr /> | ||
<PokemonSingleQueries /> | ||
</div> | ||
) | ||
} |
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,64 @@ | ||
import * as React from 'react' | ||
import { useSuspendAll } from '@reduxjs/toolkit/query/react' | ||
import { useGetPokemonByNameQuery } from './services/pokemon' | ||
import type { PokemonName } from './pokemon.data' | ||
|
||
const intervalOptions = [ | ||
{ label: 'Off', value: 0 }, | ||
{ label: '20s', value: 10000 }, | ||
{ label: '1m', value: 60000 }, | ||
] | ||
|
||
const getRandomIntervalValue = () => | ||
intervalOptions[Math.floor(Math.random() * intervalOptions.length)].value | ||
|
||
export interface PokemonProps { | ||
name: PokemonName | ||
} | ||
|
||
export function Pokemon({ name }: PokemonProps) { | ||
const [pollingInterval, setPollingInterval] = React.useState( | ||
getRandomIntervalValue() | ||
) | ||
|
||
const [{ data, isFetching, refetch }] = useSuspendAll( | ||
useGetPokemonByNameQuery(name) | ||
) | ||
|
||
return ( | ||
<section className="pokemon-card"> | ||
<h3>{data.species.name}</h3> | ||
<img | ||
src={data.sprites.front_shiny} | ||
alt={data.species.name} | ||
className={'pokemon-card__pic'} | ||
style={{ ...(isFetching ? { opacity: 0.3 } : {}) }} | ||
/> | ||
<div> | ||
<label style={{ display: 'block' }}>Polling interval</label> | ||
<select | ||
value={pollingInterval} | ||
onChange={({ target: { value } }) => | ||
setPollingInterval(Number(value)) | ||
} | ||
> | ||
{intervalOptions.map(({ label, value }) => ( | ||
<option key={value} value={value}> | ||
{label} | ||
</option> | ||
))} | ||
</select> | ||
</div> | ||
<div> | ||
<button | ||
type="button" | ||
className={'btn'} | ||
onClick={refetch} | ||
disabled={isFetching} | ||
> | ||
{isFetching ? 'Loading' : 'Manually refetch'} | ||
</button> | ||
</div> | ||
</section> | ||
) | ||
} |
93 changes: 93 additions & 0 deletions
93
examples/query/react/suspense/src/PokemonParallelQueries.tsx
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,93 @@ | ||
import * as React from 'react' | ||
import { ErrorBoundary } from 'react-error-boundary' | ||
import { pokemonEvolutions } from './pokemon.data' | ||
import { PokemonPlaceholder } from './PokemonPlaceholder' | ||
import { PokemonWithEvolution } from './PokemonWithEvolution' | ||
|
||
const evolutionsKeys = Object.keys( | ||
pokemonEvolutions | ||
) as (keyof typeof pokemonEvolutions)[] | ||
|
||
export const PokemonParallelQueries = React.memo( | ||
function PokemonParallelQueries() { | ||
const [evolutions, setEvolutions] = React.useState([ | ||
'bulbasaur' as keyof typeof pokemonEvolutions, | ||
]) | ||
|
||
return ( | ||
<article className="parallel-queries"> | ||
<h2>Suspense: indipendent parallel queries</h2> | ||
<form | ||
className="select-pokemon-form" | ||
action="#" | ||
onSubmit={(evt) => { | ||
evt.preventDefault() | ||
|
||
const formValues = new FormData(evt.currentTarget) | ||
|
||
const next = Boolean(formValues.get('addBulbasaur')) | ||
? 'bulbasaur' | ||
: evolutionsKeys[ | ||
Math.floor(Math.random() * evolutionsKeys.length) | ||
] | ||
|
||
setEvolutions((curr) => curr.concat(next)) | ||
}} | ||
> | ||
<label htmlFor="addBulbasaurandEvolution"> | ||
addBulbasaur | ||
<input | ||
type="checkbox" | ||
name="addBulbasaur" | ||
id="addBulbasaurandEvolution" | ||
/> | ||
</label> | ||
<button type="submit">Add pokemon + evolution</button> | ||
</form> | ||
<div className="pokemon-list"> | ||
{evolutions.map((name, idx) => ( | ||
<ErrorBoundary | ||
key={idx} | ||
onError={console.error} | ||
fallbackRender={({ resetErrorBoundary, error }) => ( | ||
<> | ||
<PokemonPlaceholder | ||
name={name} | ||
error={error} | ||
onRetry={() => { | ||
(error as any)?.retryQuery?.(); | ||
resetErrorBoundary() | ||
}} | ||
/> | ||
<PokemonPlaceholder | ||
name={pokemonEvolutions[name]} | ||
error={error} | ||
onRetry={() => { | ||
(error as any)?.retryQuery?.() | ||
resetErrorBoundary() | ||
}} | ||
/> | ||
</> | ||
)} | ||
> | ||
<React.Suspense | ||
fallback={ | ||
<> | ||
<PokemonPlaceholder name={name} /> | ||
<PokemonPlaceholder name={pokemonEvolutions[name]} /> | ||
</> | ||
} | ||
> | ||
<PokemonWithEvolution | ||
key={idx} | ||
base={name} | ||
evolution={pokemonEvolutions[name]} | ||
/> | ||
</React.Suspense> | ||
</ErrorBoundary> | ||
))} | ||
</div> | ||
</article> | ||
) | ||
} | ||
) |
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,55 @@ | ||
import * as React from 'react' | ||
import clsx from 'clsx' | ||
import { PokemonName } from './pokemon.data' | ||
|
||
export interface PokemonPlaceholderProps | ||
extends React.HTMLAttributes<HTMLDivElement> { | ||
name: PokemonName | ||
error?: Error | undefined | ||
onRetry?(): void | ||
} | ||
|
||
export function PokemonPlaceholder({ | ||
name, | ||
children, | ||
className, | ||
error, | ||
onRetry, | ||
...otherProps | ||
}: PokemonPlaceholderProps) { | ||
const isError = !!error | ||
|
||
let content: React.ReactNode = isError ? ( | ||
<> | ||
<h3>An error has occurred while loading {name}</h3> | ||
<div>{error?.message}</div> | ||
{onRetry && ( | ||
<button type="button" className="btn" onClick={onRetry}> | ||
retry | ||
</button> | ||
)} | ||
{children} | ||
</> | ||
) : ( | ||
<> | ||
<h3>Loading pokemon {name}</h3> | ||
<br /> | ||
(Suspense fallback) | ||
{children} | ||
</> | ||
) | ||
|
||
return ( | ||
<section | ||
className={clsx( | ||
'pokemon-card', | ||
'pokemon-cart--placeholder', | ||
{ 'alert--danger': isError, 'alert--info': !isError }, | ||
className | ||
)} | ||
{...otherProps} | ||
> | ||
{content} | ||
</section> | ||
) | ||
} |
Oops, something went wrong.