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