Open History to see the last commit
1import { queryOptions, skipToken } from '@tanstack/react-query'
2β
3type Film = {
4 title: string
5 episode_id: number
6 opening_crawl: string
7 release_date: string
8 characters: Array<string>
9 url: string
10}
11β
12type Character = {
13 name: string
14 height: string
15 mass: string
16 hair_color: string
17 eye_color: string
18 birth_year: string
19 homeworld: string
20 films: Array<string>
21 url: string
22}
23β
24type Planet = {
25 name: string
26}
27β
28type Paginated<T> = {
29 results: Array<T>
30}
31β
32const getFilms = async (): Promise<Paginated<Film>> => {
33 const res = await fetch('https://swapi.dev/api/films/')
34 if (!res.ok) throw new Error('Failed to fetch films')
35 return await res.json()
36}
37β
38const getFilm = async (filmId: string): Promise<Film> => {
39 const res = await fetch(`https://swapi.dev/api/films/${filmId}/`)
40 if (!res.ok) throw new Error('Failed to fetch film')
41 return await res.json()
42}
43β
44const getCharacters = async (): Promise<Paginated<Character>> => {
45 const res = await fetch('https://swapi.dev/api/people/')
46 if (!res.ok) throw new Error('Failed to fetch characters')
47 return await res.json()
48}
49β
50const getCharacter = async (characterId: string): Promise<Character> => {
51 const res = await fetch(`https://swapi.dev/api/people/${characterId}/`)
52 if (!res.ok) throw new Error('Failed to fetch character')
53 return await res.json()
54}
55β
56const getPlanet = async (planetId: string): Promise<Planet> => {
57 const res = await fetch(`https://swapi.dev/api/planets/${planetId}/`)
58 if (!res.ok) throw new Error('Failed to fetch planet')
59 return await res.json()
60}
61β
62export const filmsQueryOptions = queryOptions({
63 queryKey: ['films'],
64 queryFn: getFilms,
65})
66β
67export const filmQueryOptions = (filmId: string | undefined) =>
68 queryOptions({
69 queryKey: ['film', filmId],
70 queryFn: filmId ? () => getFilm(filmId) : skipToken,
71 })
72β
73export const charactersQueryOptions = queryOptions({
74 queryKey: ['characters'],
75 queryFn: getCharacters,
76})
77β
78export const characterQueryOptions = (characterId: string) =>
79 queryOptions({
80 queryKey: ['character', characterId],
81 queryFn: () => getCharacter(characterId),
82 })
83β
84export const homeworldQueryOptions = (homeworldId: string) =>
85 queryOptions({
86 queryKey: ['homeworld', homeworldId],
87 queryFn: () => getPlanet(homeworldId),
88 })