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

batching-requests-using-bathshit.md

75 lines2.9 KB

1---
2id: batching-requests
3title: Batching Requests
4---
5​
6Many times we want to batch the requests a program(or component) does into one single request that fetches all the data items needed to execute(render) the program.
7​
8Lets say you have a component `<UserDetails userId={1}>` that internally fetches the user data and displays the user details. But it might be used arbitrarily on the page, for example in a user list, but also in the sidebar containing some messages and the details of the user that sent it.
9​
10The problem is that orchestrating a single fetch for all rendered user details components can be complex and has to be done in a parent component or state management module.
11​
12## What we want
13​
14- We want to define a component that fetches and renders the user details by a user id.
15- We want to batch the requests for user details made by all rendered components that are on the page at a given time.
16- If one or more components are rendered within `10 ms` we batch those requests.
17- If one or more components are rendered after the window of `10ms`, we batch those subsequent requests.
18​
19## Implementation
20​
21First lets setup a batcher using [@yornaath/batshit](https://www.npmjs.com/package/@yornaath/batshit)
22​
23```ts
24import { Batcher, windowScheduler, keyResolver } from "@yornaath/batshit"
25​
26type User = { id: number, name: string }
27​
28const users = Batcher<User, number>({
29 // The fetcher resolves the list of queries(here just a list of user ids as number) to one single api call.
30 fetcher: async (ids: number[]) => {
31 return api.users.where({
32 userId_in: ids
33 })
34 },
35 // when we call users.fetch, this will resolve the correct user using the field `id`
36 resolver: keyResolver("id"),
37 // this will batch all calls to users.fetch that are made within 10 milliseconds.
38 scheduler: windowScheduler(10)
39})
40```
41​
42Then we can define our query hook that uses the batcher. If this hook is used(rendered) in multiple places within our app within the 10 millisecond window we gave, all those requests will be batched. Caching and deduplication is of course handled by react-query.
43​
44```ts
45const useUser = (id: number) => {
46 return useQuery([ "users", id ], async () => {
47 return users.fetch(id)
48 })
50```
51​
52> Note: Developer ux remains the same as if the hook fetched the items individually as single requests and can be used arbitrarily across your codebase.
53​
54Finally lets define our user details component that consumes the hook we made.
55​
56```ts
57const UserDetails = (props: {userId: number}) => {
58 const {isLoading, data} = useUser(props.userId)
59 return <>
60 {
61 isLoading ?
62 <div>Loading user {props.userId}</div>
63 :
64 <div>
65 User: {data.name}
66 </div>
67 }
68 </>
70```
71​
72### batshit docs
73​
74For more information about how to create batchers with custom resolving and request scheduling please refer to the batshit repo readme
75over at the [yornaath/batshit github repository](https://github.com/yornaath/batshit/)