Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.tsx

122 lines3.1 KB

1import { render } from 'preact'
2import { useState } from 'preact/hooks'
3import {
4 QueryClient,
5 QueryClientProvider,
6 useQueries,
7} from '@tanstack/preact-query'
8import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
9import { charactersQueries } from './services/characters/queries'
10​
11const queryClient = new QueryClient({
12 defaultOptions: {
13 queries: {
14 retry: 0,
15 },
16 },
17})
18​
19function Characters({ ids }: { ids: Array<number> }) {
20 const characters = useQueries({
21 queries: ids.map((id) => charactersQueries.detail(id)),
22 })
23​
24 return characters.map((character, index) => {
25 if (character.status === 'pending') {
26 return 'Loading...'
27 }
28 if (character.status === 'error') {
29 return 'Error...'
30 }
31 if (character.data === null) {
32 return 'Not found ...'
33 }
34​
35 return (
36 <div key={String(index)} style={{ display: 'flex' }}>
37 <img
38 width={100}
39 height={100}
40 alt={character.data.image}
41 src={character.data.image}
42 />
43 <div style={{ paddingLeft: 10, textAlign: 'left' }}>
44 <h5 style={{ marginTop: 0, marginBottom: 5 }}>
45 {character.data.name} (#{character.data.id})
46 </h5>
47 <p style={{ marginTop: 0, marginBottom: 2 }}>
48 Status: {character.data.status}
49 </p>
50 <p style={{ marginTop: 0, marginBottom: 2 }}>
51 Species: {character.data.species}
52 </p>
53 <p style={{ marginTop: 0, marginBottom: 2 }}>
54 Gender: {character.data.gender}
55 </p>
56 </div>
57 </div>
58 )
59 })
61​
62function App() {
63 const [ids, setIds] = useState<Array<number>>([])
64 const [idsToLoad, setIdsToLoad] = useState<Array<number>>([])
65 const [error, setError] = useState('')
66​
67 return (
68 <div className="App">
69 <h2>Character fetcher</h2>
70 <div>
71 <label style={{ display: 'block' }}>
72 Character ids (numeric, comma separated)
73 </label>
74 <input
75 style={{ display: 'inline-block' }}
76 placeholder="ids"
77 onInput={(event) => {
78 const parsedIds = event.currentTarget.value
79 .split(',')
80 .map((id) => id.trim())
81​
82 if (parsedIds.every((id) => /^\d+$/.test(id))) {
83 setIds(parsedIds.map(Number))
84 setError('')
85 } else {
86 setError('Invalid.. only use numbers and comma')
87 }
88 }}
89 />
90 </div>
91​
92 {error ? <h3 style={{ color: 'red' }}>{error}</h3> : null}
93​
94 <button
95 type="button"
96 disabled={!!error}
97 onClick={() => {
98 setIdsToLoad(ids)
99 }}
100 >
101 Load characters
102 </button>
103 <div>
104 <h4 style={{ textAlign: 'left' }}>Characters:</h4>
105 <Characters ids={idsToLoad} />
106 </div>
107 </div>
108 )
110​
111function Root() {
112 return (
113 <QueryClientProvider client={queryClient}>
114 <App />
115 <PreactQueryDevtools initialIsOpen />
116 </QueryClientProvider>
117 )
119​
120const rootElement = document.getElementById('root')
121if (!rootElement) throw new Error('Missing #root element')
122render(<Root />, rootElement)