|
| 1 | +import * as React from 'react' |
| 2 | +import { pokemonApi } from './services/pokemon' |
| 3 | +import type { PokemonName } from './pokemon.data' |
| 4 | + |
| 5 | +const intervalOptions = [ |
| 6 | + { label: 'Off', value: 0 }, |
| 7 | + { label: '20s', value: 10000 }, |
| 8 | + { label: '1m', value: 60000 }, |
| 9 | +] |
| 10 | + |
| 11 | +const getRandomIntervalValue = () => |
| 12 | + intervalOptions[Math.floor(Math.random() * intervalOptions.length)].value |
| 13 | + |
| 14 | +export const Pokemon = ({ |
| 15 | + name, |
| 16 | + suspendOnRefetch = false, |
| 17 | +}: { |
| 18 | + name: PokemonName |
| 19 | + suspendOnRefetch?: boolean |
| 20 | +}) => { |
| 21 | + const [pollingInterval, setPollingInterval] = React.useState( |
| 22 | + getRandomIntervalValue() |
| 23 | + ) |
| 24 | + |
| 25 | + const { data, isFetching, refetch } = |
| 26 | + pokemonApi.endpoints.getPokemonByName.useUnstable_SuspenseQuery(name, { |
| 27 | + pollingInterval, |
| 28 | + suspendOnRefetch, |
| 29 | + }) |
| 30 | + |
| 31 | + if (!data) { |
| 32 | + return ( |
| 33 | + <section> |
| 34 | + <h3>{name}</h3> |
| 35 | + <p>No data!</p> |
| 36 | + </section> |
| 37 | + ) |
| 38 | + } |
| 39 | + |
| 40 | + return ( |
| 41 | + <section> |
| 42 | + <h3>{data.species.name}</h3> |
| 43 | + <div style={{ minWidth: 96, minHeight: 96 }}> |
| 44 | + <img |
| 45 | + src={data.sprites.front_shiny} |
| 46 | + alt={data.species.name} |
| 47 | + style={{ ...(isFetching ? { opacity: 0.3 } : {}) }} |
| 48 | + /> |
| 49 | + </div> |
| 50 | + <div> |
| 51 | + <label style={{ display: 'block' }}>Polling interval</label> |
| 52 | + <select |
| 53 | + value={pollingInterval} |
| 54 | + onChange={({ target: { value } }) => |
| 55 | + setPollingInterval(Number(value)) |
| 56 | + } |
| 57 | + > |
| 58 | + {intervalOptions.map(({ label, value }) => ( |
| 59 | + <option key={value} value={value}> |
| 60 | + {label} |
| 61 | + </option> |
| 62 | + ))} |
| 63 | + </select> |
| 64 | + </div> |
| 65 | + <div> |
| 66 | + <p>suspendOnRefetch: {String(suspendOnRefetch)}</p> |
| 67 | + <button onClick={refetch} disabled={isFetching}> |
| 68 | + {isFetching ? 'Loading' : 'Manually refetch'} |
| 69 | + </button> |
| 70 | + </div> |
| 71 | + </section> |
| 72 | + ) |
| 73 | +} |
0 commit comments