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

Character.tsx

111 lines3.2 KB

1import { A, useParams } from '@solidjs/router'
2import { useQuery } from '@tanstack/solid-query'
3import { For, Match, Show, Switch } from 'solid-js'
4import { charactersQueries } from './services/characters/queries'
5import { episodesQueries } from './services/episodes/queries'
6import { locationsQueries } from './services/locations/queries'
7​
8function Character() {
9 const params = useParams<{ characterId: string }>()
10​
11 const query = useQuery(() => charactersQueries.detail(params.characterId))
12​
13 return (
14 <Switch>
15 <Match when={query.status === 'pending'}>
16 <p>Loading...</p>
17 </Match>
18 <Match when={query.status === 'error'}>
19 <p>Error :(</p>
20 </Match>
21 <Match when={query.data}>
22 {(data) => {
23 const locationId = () => {
24 const locationUrlParts = data()
25 .location.url.split('/')
26 .filter(Boolean)
27 return locationUrlParts[locationUrlParts.length - 1]
28 }
29​
30 return (
31 <div>
32 <h2 class="text-4xl">{data().name}</h2>
33 <p>
34 <strong>Gender</strong>: {data().gender}
35 </p>
36 <p>
37 <strong>Status</strong>: {data().status}
38 </p>
39 <p>
40 <strong>Species</strong>: {data().species}
41 </p>
42 <p>
43 <strong>Origin</strong>: {data().origin.name}
44 </p>
45 <p>
46 <strong>Location</strong>:{' '}
47 <Show when={locationId()} fallback={data().location.name}>
48 {(id) => <Location locationId={id()} />}
49 </Show>
50 </p>
51​
52 <h4 class="text-2xl pt-4">Episodes</h4>
53 <For each={data().episode}>
54 {(episode) => {
55 const episodeUrlParts = episode.split('/').filter(Boolean)
56 const episodeId = episodeUrlParts[episodeUrlParts.length - 1]
57 return <Episode episodeId={episodeId} />
58 }}
59 </For>
60 </div>
61 )
62 }}
63 </Match>
64 </Switch>
65 )
67​
68function Episode(props: { episodeId: string }) {
69 const query = useQuery(() => episodesQueries.detail(props.episodeId))
70​
71 return (
72 <Show when={query.status === 'success' && query.data}>
73 {(data) => (
74 <article>
75 <A
76 class="text-blue-500 hover:underline"
77 href={`/episodes/${props.episodeId}`}
78 >
79 <h6 class="text-lg">
80 {data().episode}. {data().name} - {data().air_date}
81 </h6>
82 </A>
83 </article>
84 )}
85 </Show>
86 )
88​
89function Location(props: { locationId: string }) {
90 const query = useQuery(() => locationsQueries.detail(props.locationId))
91​
92 return (
93 <Switch>
94 <Match when={query.status === 'pending'}>
95 <span>Loading...</span>
96 </Match>
97 <Match when={query.status === 'error'}>
98 <span>Error :(</span>
99 </Match>
100 <Match when={query.data}>
101 {(data) => (
102 <span>
103 {data().name} - {data().type}
104 </span>
105 )}
106 </Match>
107 </Switch>
108 )
110​
111export default Character