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

SolidApp.tsx

250 lines7.2 KB

1import {
2 QueryClient,
3 QueryClientProvider,
4 createQuery,
5 keepPreviousData,
6} from '@tanstack/solid-query'
7import { SolidQueryDevtools } from '@tanstack/solid-query-devtools'
8import {
9 For,
10 Show,
11 Suspense,
12 createContext,
13 createSignal,
14 useContext,
15} from 'solid-js'
16import { Link } from './Link'
17import { getSearchParams, properCase } from '../utils'
18import { isServer } from 'solid-js/web'
19​
20const PokemonIdContext = createContext<() => string>()
21​
22const usePokemonID = () => {
23 const id = useContext(PokemonIdContext)
24 if (!id) throw new Error('PokemonIdContext not found')
25 return id
27​
28const MAX_POKEMONS = 100
29​
30export const SolidApp = (props: { pokemon?: string }) => {
31 const client = new QueryClient()
32​
33 const search = getSearchParams(props.pokemon || '')
34​
35 return (
36 <QueryClientProvider client={client}>
37 <SolidQueryDevtools />
38 <Suspense fallback={'Loading'}>
39 <PokemonIdContext.Provider value={search}>
40 <App />
41 </PokemonIdContext.Provider>
42 </Suspense>
43 </QueryClientProvider>
44 )
46​
47const App = () => {
48 return (
49 <div class="flex flex-1 overflow-auto">
50 <SideNav />
51 <PokemonDetails />
52 </div>
53 )
55​
56const PokemonDetails = () => {
57 const id = usePokemonID()
58 return (
59 <div class="flex-1 flex">
60 <Show when={id()}>
61 <Suspense fallback={'Loading'}>
62 <PokemonDex id={id()} />
63 </Suspense>
64 </Show>
65 <Show when={!id()}>
66 <div class="justify-center items-center flex-1 flex text-2xl font-medium text-zinc-700">
67 <div class="">Select a pokemon to see its stats</div>
68 </div>
69 </Show>
70 </div>
71 )
73​
74const PokemonDex = (props: { id: string }) => {
75 const pokemon = createQuery(() => ({
76 queryKey: ['pokemon', props.id],
77 queryFn: async () => {
78 const res = await fetch(
79 `https://pokeapi.co/api/v2/pokemon/${props.id}`,
80 ).then((res) => res.json())
81 return res
82 },
83 placeholderData: keepPreviousData,
84 }))
85​
86 const pokemon_stats = createQuery(() => ({
87 queryKey: ['pokemon', props.id],
88 queryFn: async () => {
89 const res = await fetch(
90 `https://pokeapi.co/api/v2/pokemon/${props.id}`,
91 ).then((res) => res.json())
92​
93 return res
94 },
95 select(data) {
96 const nameMap = {
97 hp: 'HP',
98 attack: 'Attack',
99 defense: 'Defense',
100 'special-attack': 'Special Attack',
101 'special-defense': 'Special Defense',
102 speed: 'Speed',
103 }
104 const stats = data.stats.map((stat: any) => ({
105 name: nameMap[stat.stat.name as keyof typeof nameMap],
106 value: stat.base_stat,
107 }))
108 return stats as { name: string; value: number }[]
109 },
110 placeholderData: keepPreviousData,
111 reconcile: 'name',
112 }))
113​
114 const is_server_rendered = createQuery(() => ({
115 queryKey: ['is_server_rendered', props.id],
116 queryFn: () => {
117 if (isServer) return true
118 return false
119 },
120 placeholderData: keepPreviousData,
121 }))
122​
123 return (
124 <div class="flex flex-col flex-1">
125 <Show when={pokemon.data}>
126 <div class="flex justify-center text-3xl font-semibold py-4">
127 {properCase(pokemon.data.name)}
128 </div>
129 <div class="flex justify-center">
130 <div class="h-64 w-64 rounded-lg relative overflow-hidden border">
131 <img
132 class="h-[400%] w-[400%] max-w-[400%] object-contain blur-2xl brightness-125 contrast-150 absolute z-10 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"
133 src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${props.id}.png`}
134 alt={properCase(pokemon.data?.name || '')}
135 />
136 <img
137 class="h-full w-full object-contain relative z-20"
138 src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${props.id}.png`}
139 alt={properCase(pokemon.data?.name || '')}
140 />
141 </div>
142 </div>
143 </Show>
144​
145 <div class="flex justify-center py-4">
146 <div>
147 This query was rendered on the{' '}
148 <Show
149 when={is_server_rendered.data}
150 fallback={
151 <>
152 <b>client</b>. Reload this page to see the page rendered on the
153 server.
154 </>
155 }
156 >
157 <b>server. </b>
158 Click on another pokemon to see queries run and render on the
159 client.
160 </Show>
161 </div>
162 </div>
163​
164 <Show when={pokemon_stats.data}>
165 <div class="flex justify-center flex-col gap-2">
166 <For each={pokemon_stats.data}>
167 {(stat) => (
168 <div class="flex gap-2 justify-center items-center">
169 <div class="w-36">{stat.name}</div>
170 <div class="w-80 h-8 relative bg-zinc-100 rounded overflow-hidden flex justify-center items-center">
171 <div
172 class="absolute z-10 h-full top-0 left-0 bg-lime-300"
173 style={{
174 width: `${(stat.value / 160) * 100}%`,
175 transition: 'width 0.5s',
176 }}
177 ></div>
178 <div class="relative z-20 text-sm mix-blend-darken font-semibold">
179 {stat.value}
180 </div>
181 </div>
182 </div>
183 )}
184 </For>
185 </div>
186 </Show>
187 </div>
188 )
190​
191const SideNav = () => {
192 const id = usePokemonID()
193​
194 const pokemonsList = createQuery(() => ({
195 queryKey: ['pokemons'],
196 queryFn: async () => {
197 const res = await fetch(
198 `https://pokeapi.co/api/v2/pokemon?limit=${MAX_POKEMONS}`,
199 ).then((res) => res.json())
200 return res as {
201 results: { name: string; url: string }[]
202 }
203 },
204 select(data) {
205 return data.results.map((p) => {
206 const regex = /\/pokemon\/(\d+)\/$/
207 const match = p.url.match(regex)
208 const id = match ? match[1] : ''
209 return {
210 name: properCase(p.name),
211 id,
212 avatar: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${id}.png`,
213 }
214 })
215 },
216 placeholderData: keepPreviousData,
217 reconcile: 'id',
218 }))
219​
220 const activeClass = (pokemonID: string) =>
221 id() === pokemonID ? 'bg-gray-50' : 'hover:bg-gray-50'
222​
223 return (
224 <div class="w-72 border-r flex flex-col px-2">
225 <div class="pt-3 pb-1 text-sm font-semibold">Pokemons</div>
226​
227 <div class="flex-1 overflow-auto flex flex-col gap-1">
228 <For each={pokemonsList.data}>
229 {(pokemon) => (
230 <Link
231 class={`flex gap-2 items-center border rounded p-1 ${activeClass(
232 pokemon.id,
233 )}`}
234 href={`./?id=${pokemon.id}`}
235 >
236 <span class="flex bg-zinc-100 border relative justify-center items-center overflow-hidden rounded-sm w-9 h-9 flex-shrink-0">
237 <img
238 class="w-7 h-7 relative z-20"
239 src={pokemon.avatar}
240 alt={pokemon.name}
241 />
242 </span>
243 <span>{pokemon.name}</span>
244 </Link>
245 )}
246 </For>
247 </div>
248 </div>
249 )