|
| 1 | +import * as React from 'react' |
| 2 | +import { useSuspendAll } from '@reduxjs/toolkit/query/react' |
| 3 | +import { useGetPokemonByNameQuery } from './services/pokemon' |
| 4 | +import type { PokemonName } from './pokemon.data' |
| 5 | + |
| 6 | +const intervalOptions = [ |
| 7 | + { label: 'Off', value: 0 }, |
| 8 | + { label: '20s', value: 10000 }, |
| 9 | + { label: '1m', value: 60000 }, |
| 10 | +] |
| 11 | + |
| 12 | +const getRandomIntervalValue = () => |
| 13 | + intervalOptions[Math.floor(Math.random() * intervalOptions.length)].value |
| 14 | + |
| 15 | +export interface PokemonProps { |
| 16 | + name: PokemonName |
| 17 | +} |
| 18 | + |
| 19 | +export function Pokemon({ name }: PokemonProps) { |
| 20 | + const [pollingInterval, setPollingInterval] = React.useState( |
| 21 | + getRandomIntervalValue() |
| 22 | + ) |
| 23 | + |
| 24 | + const [{ data, isFetching, refetch }] = useSuspendAll( |
| 25 | + useGetPokemonByNameQuery(name) |
| 26 | + ) |
| 27 | + |
| 28 | + return ( |
| 29 | + <section className="pokemon-card"> |
| 30 | + <h3>{data.species.name}</h3> |
| 31 | + <img |
| 32 | + src={data.sprites.front_shiny} |
| 33 | + alt={data.species.name} |
| 34 | + className={'pokemon-card__pic'} |
| 35 | + style={{ ...(isFetching ? { opacity: 0.3 } : {}) }} |
| 36 | + /> |
| 37 | + <div> |
| 38 | + <label style={{ display: 'block' }}>Polling interval</label> |
| 39 | + <select |
| 40 | + value={pollingInterval} |
| 41 | + onChange={({ target: { value } }) => |
| 42 | + setPollingInterval(Number(value)) |
| 43 | + } |
| 44 | + > |
| 45 | + {intervalOptions.map(({ label, value }) => ( |
| 46 | + <option key={value} value={value}> |
| 47 | + {label} |
| 48 | + </option> |
| 49 | + ))} |
| 50 | + </select> |
| 51 | + </div> |
| 52 | + <div> |
| 53 | + <button |
| 54 | + type="button" |
| 55 | + className={'btn'} |
| 56 | + onClick={refetch} |
| 57 | + disabled={isFetching} |
| 58 | + > |
| 59 | + {isFetching ? 'Loading' : 'Manually refetch'} |
| 60 | + </button> |
| 61 | + </div> |
| 62 | + </section> |
| 63 | + ) |
| 64 | +} |
0 commit comments