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

SolidApp.tsx

251 lines7.3 KB

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