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(rtk-query/react): add useUnstable_SuspenseQuery hook #2149

Closed
Closed
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions .codesandbox/ci.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"github/reduxjs/rtk-github-issues-example",
"/examples/query/react/basic",
"/examples/query/react/advanced",
"/examples/query/react/suspense",
"/examples/action-listener/counter"
],
"node": "14",
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
40 changes: 40 additions & 0 deletions examples/query/react/suspense/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "@examples-query-react/suspense",
"private": true,
"version": "1.0.0",
"description": "",
"keywords": [],
"main": "src/index.tsx",
"dependencies": {
"@reduxjs/toolkit": "^1.6.0-rc.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"
},
"devDependencies": {
"@types/react": "17.0.0",
"@types/react-dom": "17.0.0",
"@types/react-redux": "7.1.9",
"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"
]
}
43 changes: 43 additions & 0 deletions examples/query/react/suspense/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!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"
}
68 changes: 68 additions & 0 deletions examples/query/react/suspense/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import * as React from 'react'
import { POKEMON_NAMES } from './pokemon.data'
import './styles.css'
import { SuspendedPokemon, SuspendedPokemonProps } from './SuspendedPokemon'

const getRandomPokemonName = () =>
POKEMON_NAMES[Math.floor(Math.random() * POKEMON_NAMES.length)]

export default function App() {
const [pokemonConf, setPokemonConf] = React.useState<SuspendedPokemonProps[]>(
[{ name: 'bulbasaur', suspendOnRefetch: false, throwOnIntialRender: false }]
)

return (
<div className="App">
<div>
<form
action="#"
onSubmit={(evt) => {
evt.preventDefault()

const formValues = new FormData(evt.currentTarget)

setPokemonConf((prev) => [
...prev,
{
name: Boolean(formValues.get('addBulbasaur'))
? 'bulbasaur'
: getRandomPokemonName(),
suspendOnRefetch: Boolean(formValues.get('suspendOnRefetch')),
throwOnIntialRender: Boolean(
formValues.get('throwOnIntialRender')
),
},
])
}}
>
<label htmlFor="suspendOnRefetch">
suspendOnRefetch
<input
type="checkbox"
name="suspendOnRefetch"
id="suspendOnRefetch"
/>
</label>
<label htmlFor="addBulbasaur">
addBulbasaur
<input type="checkbox" name="addBulbasaur" id="addBulbasaur" />
</label>
<label htmlFor="throwOnIntialRender">
throwOnIntialRender
<input
type="checkbox"
name="throwOnIntialRender"
id="throwOnIntialRender"
/>
</label>
<button>Add pokemon</button>
</form>
</div>
<div className="pokemon-list">
{pokemonConf.map((suspendedPokemonProps, index) => (
<SuspendedPokemon key={index} {...suspendedPokemonProps} />
))}
</div>
</div>
)
}
73 changes: 73 additions & 0 deletions examples/query/react/suspense/src/Pokemon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import * as React from 'react'
import { pokemonApi } 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 const Pokemon = ({
name,
suspendOnRefetch = false,
}: {
name: PokemonName
suspendOnRefetch?: boolean
}) => {
const [pollingInterval, setPollingInterval] = React.useState(
getRandomIntervalValue()
)

const { data, isFetching, refetch } =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a way to type isFetching as void or remove it from the return value if suspendOnRefetch is true?

if suspendOnRefetch is true, isFetching is always going to be false when accessed in user code

Copy link
Contributor Author

@FaberVitale FaberVitale Mar 26, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a way to type isFetching as void or remove it from the return value if suspendOnRefetch is true?

if suspendOnRefetch is true, isFetching is always going to be false when accessed in user code

You can play with ts types in order to have isFetching be always true if suspendOnRefetch is set to true but,

no I don't think that we should remove isFetching from the response.

pokemonApi.endpoints.getPokemonByName.useUnstable_SuspenseQuery(name, {
pollingInterval,
suspendOnRefetch,
})

if (!data) {
return (
<section>
<h3>{name}</h3>
<p>No data!</p>
</section>
)
}

return (
<section>
<h3>{data.species.name}</h3>
<div style={{ minWidth: 96, minHeight: 96 }}>
<img
src={data.sprites.front_shiny}
alt={data.species.name}
style={{ ...(isFetching ? { opacity: 0.3 } : {}) }}
/>
</div>
<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>
<p>suspendOnRefetch: {String(suspendOnRefetch)}</p>
<button onClick={refetch} disabled={isFetching}>
{isFetching ? 'Loading' : 'Manually refetch'}
</button>
</div>
</section>
)
}
60 changes: 60 additions & 0 deletions examples/query/react/suspense/src/SuspendedPokemon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { memo } from 'react';
import { Suspense, useState } from 'react'
import { Pokemon } from './Pokemon'
import { PokemonName } from './pokemon.data'
import { ErrorBoundary } from 'react-error-boundary'

export interface SuspendedPokemonProps {
name: PokemonName
suspendOnRefetch: boolean
throwOnIntialRender: boolean
}

function BuggyComponent({ errorCount, name }:Pick<SuspendedPokemonProps, 'name'> & { errorCount: number }) {
if(!errorCount) {
throw new Error(`error while rendering: ${name}, errorCount ${errorCount}`);
}

return <></>
}

export const SuspendedPokemon = memo(function SuspendedPokemon({
name,
suspendOnRefetch,
throwOnIntialRender,
}: SuspendedPokemonProps) {
const [errorCount, setErrorCount] = useState(0)

return (
<div>
<ErrorBoundary
onReset={() => setErrorCount((n) => n + 1)}
fallbackRender={({ resetErrorBoundary, error }) => {
return (
<section>
<h3>render {name} error</h3>
<p>{String(error)}</p>
<div>
<button type="button" onClick={resetErrorBoundary}>
reset error boundary
</button>
</div>
</section>
)
}}
>
{throwOnIntialRender && <BuggyComponent name={name} errorCount={errorCount} />}
<Suspense
fallback={
<div className={'suspense-fallback-wrapper'}>
Suspense fallback UI.<br />
Loading pokemon {name}
</div>
}
>
<Pokemon name={name} suspendOnRefetch={suspendOnRefetch} />
</Suspense>
</ErrorBoundary>
</div>
)
});
13 changes: 13 additions & 0 deletions examples/query/react/suspense/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { render } from 'react-dom'
import { Provider } from 'react-redux'

import App from './App'
import { store } from './store'

const rootElement = document.getElementById('root')
render(
<Provider store={store}>
<App />
</Provider>,
rootElement
)
Loading