-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathcharacter-loader.ts
More file actions
60 lines (50 loc) · 1.47 KB
/
Copy pathcharacter-loader.ts
File metadata and controls
60 lines (50 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { AsyncBatcher } from '@tanstack/react-pacer/async-batcher'
interface CharacterT {
id: number
name: string
status: string
species: string
type: string
gender: string
image: string
}
type CharacterRequest = {
deferred: PromiseWithResolvers<CharacterT | null>
id: number
}
// fetch function that returns characters by id
const fetchCharacters = async (ids: ReadonlyArray<number>) => {
console.log(`Fetching characters: ${ids.join(', ')}`)
const res = await fetch(
`https://rickandmortyapi.com/api/character/[${ids.join(',')}]`,
)
const characters = (await res.json()) as Array<CharacterT> | CharacterT
const characterMap = new Map<number, CharacterT>()
for (const character of Array.isArray(characters)
? characters
: [characters]) {
characterMap.set(character.id, character)
}
return characterMap
}
const characterBatcher = new AsyncBatcher<CharacterRequest>(
(requests) => fetchCharacters([...new Set(requests.map(({ id }) => id))]),
{
wait: 0,
onSuccess: (charactersById, requests) => {
for (const { deferred, id } of requests) {
deferred.resolve(charactersById.get(id) ?? null)
}
},
onError: (error, requests) => {
for (const { deferred } of requests) {
deferred.reject(error)
}
},
},
)
export const loadCharacter = (id: number) => {
const deferred = Promise.withResolvers<CharacterT | null>()
characterBatcher.addItem({ deferred, id })
return deferred.promise
}