Open History to see the last commit
1import { queryOptions } from '@tanstack/react-query'
2β
3type Episode = {
4 id: number
5 name: string
6 air_date: string
7 episode: string
8 characters: Array<string>
9}
10β
11type Character = {
12 id: number
13 name: string
14 status: string
15 species: string
16 gender: string
17 origin: { name: string; url: string }
18 location: { name: string; url: string }
19 episode: Array<string>
20}
21β
22type Location = {
23 id: number
24 name: string
25 type: string
26}
27β
28type Paginated<T> = {
29 results: Array<T>
30}
31β
32const getEpisodes = async (): Promise<Paginated<Episode>> => {
33 const res = await fetch('https://rickandmortyapi.com/api/episode/')
34 if (!res.ok) throw new Error('Failed to fetch episodes')
35 return await res.json()
36}
37β
38const getEpisode = async (episodeId: string): Promise<Episode> => {
39 const res = await fetch(
40 `https://rickandmortyapi.com/api/episode/${episodeId}`,
41 )
42 if (!res.ok) throw new Error('Failed to fetch episode')
43 return await res.json()
44}
45β
46const getCharacters = async (): Promise<Paginated<Character>> => {
47 const res = await fetch('https://rickandmortyapi.com/api/character/')
48 if (!res.ok) throw new Error('Failed to fetch characters')
49 return await res.json()
50}
51β
52const getCharacter = async (characterId: string): Promise<Character> => {
53 const res = await fetch(
54 `https://rickandmortyapi.com/api/character/${characterId}`,
55 )
56 if (!res.ok) throw new Error('Failed to fetch character')
57 return await res.json()
58}
59β
60const getLocation = async (locationId: string): Promise<Location> => {
61 const res = await fetch(
62 `https://rickandmortyapi.com/api/location/${locationId}`,
63 )
64 if (!res.ok) throw new Error('Failed to fetch location')
65 return await res.json()
66}
67β
68export const episodesQueryOptions = queryOptions({
69 queryKey: ['episodes'],
70 queryFn: getEpisodes,
71})
72β
73export const episodeQueryOptions = (episodeId: string) =>
74 queryOptions({
75 queryKey: ['episode', episodeId],
76 queryFn: () => getEpisode(episodeId),
77 })
78β
79export const charactersQueryOptions = queryOptions({
80 queryKey: ['characters'],
81 queryFn: getCharacters,
82})
83β
84export const characterQueryOptions = (characterId: string) =>
85 queryOptions({
86 queryKey: ['character', characterId],
87 queryFn: () => getCharacter(characterId),
88 })
89β
90export const locationQueryOptions = (locationId: string) =>
91 queryOptions({
92 queryKey: ['location', locationId],
93 queryFn: () => getLocation(locationId),
94 })