Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add useSuspendAll hook & react/suspense example #2245

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .codesandbox/ci.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"github/reduxjs/rtk-github-issues-example",
"/examples/query/react/basic",
"/examples/query/react/advanced",
"/examples/action-listener/counter"
"/examples/action-listener/counter",
"/examples/query/react/suspense"
],
"node": "14",
"buildCommand": "build:packages",
Expand Down
21 changes: 18 additions & 3 deletions docs/rtk-query/api/created-api/api-slice-utils.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,23 @@ patchCollection.undo()
#### Signature

```ts no-transpile
type PrefetchOptions = { ifOlderThan?: false | number } | { force?: boolean };
interface PrefetchActionCreatorResult {
unwrap(): Promise<void>,
abort(): void
}

type PrefetchOptions =
| {
ifOlderThan?: false | number,
keepSubscriptionFor?: number
}
| { force?: boolean, keepSubscriptionFor?: number }

const prefetch = (
endpointName: string,
arg: any,
options: PrefetchOptions
) => ThunkAction<void, any, any, AnyAction>;
) => ThunkAction<PrefetchActionCreatorResult, any, any, AnyAction>
```

- **Parameters**
Expand All @@ -171,13 +181,18 @@ const prefetch = (
- `options`: options to determine whether the request should be sent for a given situation:
- `ifOlderThan`: if specified, only runs the query if the difference between `new Date()` and the last`fulfilledTimeStamp` is greater than the given value (in seconds)
- `force`: if `true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.

- `keepSubscriptionFor`: how long in seconds before the data retrieved is considered unused;
defaults to `api.config.keepPrefetchSubscriptionsFor`.
#### Description

A Redux thunk action creator that can be used to manually trigger pre-fetching of data.

The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.

The output is an object with methods:
- `unwrap`: returns a promise that resolves to `undefined` when there are no pending requests initiated by this thunk.
- `abort`: cancels pending requests.

React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch the thunk action creator result internally as needed when you call the prefetching function supplied by the hook.

#### Example
Expand Down
14 changes: 12 additions & 2 deletions docs/rtk-query/api/created-api/hooks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -586,24 +586,34 @@ const prefetchCallback = api.usePrefetch(endpointName, options)
#### Signature

```ts no-transpile
interface PrefetchActionCreatorResult {
// resolves when there are no pending request.
unwrap(): Promise<void>
// cancels pending requests.
abort(): void
}

type UsePrefetch = (
endpointName: string,
options?: UsePrefetchOptions
) => PrefetchCallback

type UsePrefetchOptions =
| {
// how long is seconds before the data retrived by this prefetch request is considered unused.
keepSubscriptionFor?: number
// If specified, only runs the query if the difference between `new Date()` and the last
// `fulfilledTimeStamp` is greater than the given value (in seconds)
ifOlderThan?: false | number
}
| {
keepSubscriptionFor?: number
// If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query
// will be run even if it exists in the cache.
force?: boolean
}

type PrefetchCallback = (arg: any, options?: UsePrefetchOptions) => void
type PrefetchCallback = (arg: any, options?: UsePrefetchOptions) => PrefetchActionCreatorResult
```

- **Parameters**
Expand All @@ -612,7 +622,7 @@ type PrefetchCallback = (arg: any, options?: UsePrefetchOptions) => void
- `options`: A set of options that control whether the prefetch request should occur

- **Returns**
- A `prefetch` callback that when called, will initiate fetching the data for the provided endpoint
- A `prefetch` callback that when called, will initiate fetching the data for the provided endpoint and will return `PrefetchActionCreatorResult`.

#### Description

Expand Down
15 changes: 11 additions & 4 deletions docs/rtk-query/usage/prefetching.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,23 @@ Similar to the [`useMutation`](./mutations) hook, the `usePrefetch` hook will no
It accepts two arguments: the first is the key of a query action that you [defined in your API service](../api/createApi#endpoints), and the second is an object of two optional parameters:

```ts title="usePrefetch Signature" no-transpile
export interface PrefetchActionCreatorResult {
unwrap(): Promise<void>,
abort(): void
}

export type PrefetchOptions =
| { force?: boolean }
| {
ifOlderThan?: false | number;
};
ifOlderThan?: false | number,
keepSubscriptionFor?: number
}
| { force?: boolean, keepSubscriptionFor?: number }


usePrefetch<EndpointName extends QueryKeys<Definitions>>(
endpointName: EndpointName,
options?: PrefetchOptions
): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;
): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => PrefetchActionCreatorResult;
```

### Customizing the Hook Behavior
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const getColorForStatus = (status: Post['status']) => {
const PostList = () => {
const [page, setPage] = useState(1)
const { data: posts, isLoading, isFetching } = useListPostsQuery(page)
const prefetchPage = usePrefetch('listPosts')
const prefetchPage = usePrefetch('listPosts', { keepSubscriptionFor: 5 })

const prefetchNext = useCallback(() => {
prefetchPage(page + 1)
Expand Down
1 change: 1 addition & 0 deletions examples/query/react/suspense/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
43 changes: 43 additions & 0 deletions examples/query/react/suspense/package.json
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"
]
}
42 changes: 42 additions & 0 deletions examples/query/react/suspense/public/index.html
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>
8 changes: 8 additions & 0 deletions examples/query/react/suspense/public/manifest.json
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"
}
46 changes: 46 additions & 0 deletions examples/query/react/suspense/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
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 className='fixed-toolbar'>
<h1>Suspense</h1>
<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>
)
}
64 changes: 64 additions & 0 deletions examples/query/react/suspense/src/Pokemon.tsx
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>
)
}
Loading