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

Character.tsx

102 lines2.9 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 { filmsQueries } from './services/films/queries'
6import { planetsQueries } from './services/planets/queries'
7​
8export default function 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 homeworldId = () => {
24 const homeworldUrlParts = data()
25 .homeworld.split('/')
26 .filter(Boolean)
27 return homeworldUrlParts[homeworldUrlParts.length - 1]
28 }
29​
30 return (
31 <div>
32 <h2 class="text-4xl">{data().name}</h2>
33 <p>
34 <strong>Born</strong>: {data().birth_year}
35 </p>
36 <p>
37 <strong>Eyes</strong>: {data().eye_color}
38 </p>
39 <p>
40 <strong>Hair</strong>: {data().hair_color}
41 </p>
42 <p>
43 <strong>Height</strong>: {data().height}
44 </p>
45 <p>
46 <strong>Mass</strong>: {data().mass}
47 </p>
48 <p>
49 <strong>Homeworld</strong>:{' '}
50 <Homeworld homeworldId={homeworldId()} />
51 </p>
52​
53 <h4 class="text-2xl pt-4">Films</h4>
54 <For each={data().films}>
55 {(film) => {
56 const filmUrlParts = film.split('/').filter(Boolean)
57 const filmId = filmUrlParts[filmUrlParts.length - 1]
58 return <Film filmId={filmId} />
59 }}
60 </For>
61 </div>
62 )
63 }}
64 </Match>
65 </Switch>
66 )
68​
69function Film(props: { filmId: string }) {
70 const query = useQuery(() => filmsQueries.detail(props.filmId))
71​
72 return (
73 <Show when={query.status === 'success' && query.data}>
74 {(data) => (
75 <A
76 class="text-blue-500 hover:underline"
77 href={`/films/${props.filmId}`}
78 >
79 <h6 class="text-lg">
80 {data().episode_id}. {data().title}
81 </h6>
82 </A>
83 )}
84 </Show>
85 )
87​
88function Homeworld(props: { homeworldId: string }) {
89 const query = useQuery(() => planetsQueries.detail(props.homeworldId))
90​
91 return (
92 <Switch>
93 <Match when={query.status === 'pending'}>
94 <span>Loading...</span>
95 </Match>
96 <Match when={query.status === 'error'}>
97 <span>Error :(</span>
98 </Match>
99 <Match when={query.data}>{(data) => <span>{data().name}</span>}</Match>
100 </Switch>
101 )