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

Character.tsx

75 lines2.1 KB

1import { useQuery } from '@tanstack/react-query'
2import { Link as RouterLink, useParams } from 'react-router'
3import { charactersQueries } from './services/characters/queries'
4import { filmsQueries } from './services/films/queries'
5import { planetsQueries } from './services/planets/queries'
6​
7export default function Character() {
8 const params = useParams()
9 const characterId = params.characterId!
10​
11 const { status, data } = useQuery(charactersQueries.detail(characterId))
12​
13 if (status === 'pending') return <p>Loading...</p>
14 if (status === 'error') return <p>Error :(</p>
15​
16 const homeworldUrlParts = data.homeworld.split('/').filter(Boolean)
17 const homeworldId = homeworldUrlParts[homeworldUrlParts.length - 1]
18​
19 return (
20 <div>
21 <h2 className="text-4xl">{data.name}</h2>
22 <p>
23 <strong>Born</strong>: {data.birth_year}
24 </p>
25 <p>
26 <strong>Eyes</strong>: {data.eye_color}
27 </p>
28 <p>
29 <strong>Hair</strong>: {data.hair_color}
30 </p>
31 <p>
32 <strong>Height</strong>: {data.height}
33 </p>
34 <p>
35 <strong>Mass</strong>: {data.mass}
36 </p>
37 <p>
38 <strong>Homeworld</strong>: <Homeworld homeworldId={homeworldId} />
39 </p>
40​
41 <h4 className="text-2xl pt-4">Films</h4>
42 {data.films.map((film) => {
43 const filmUrlParts = film.split('/').filter(Boolean)
44 const filmId = filmUrlParts[filmUrlParts.length - 1]
45 return <Film filmId={filmId} key={`${filmId}`} />
46 })}
47 </div>
48 )
50​
51function Film({ filmId }: { filmId: string }) {
52 const { data, status } = useQuery(filmsQueries.detail(filmId))
53​
54 if (status === 'success') {
55 return (
56 <RouterLink
57 className="text-blue-500 hover:underline"
58 to={`/films/${filmId}`}
59 >
60 <h6 className="text-lg">
61 {data.episode_id}. {data.title}
62 </h6>
63 </RouterLink>
64 )
65 }
67​
68function Homeworld({ homeworldId }: { homeworldId: string }) {
69 const { data, status } = useQuery(planetsQueries.detail(homeworldId))
70​
71 if (status === 'pending') return <span>Loading...</span>
72 if (status === 'error') return <span>Error :(</span>
73​
74 return <span>{data.name}</span>