Documentation
Core Concepts
Understand the client, resources, endpoints, path variables, generated keys, and invalidation.
The mental model
This package is easier to understand if you think about it in three layers: client, resource, and endpoint.
The client stores shared settings like base URL, headers, and auth. A resource groups related endpoints like users or auth. An endpoint describes one request, such as get user or create post.
Paths and variables
Endpoint paths can be static strings or functions.
1const users = api.resource("users", {2 // Static path: the URL path is always the same.3 list: api.get<User[]>("/users"),4 5 // Function path: the URL path is built from variables.6 detail: api.get<User, string>((id) => `/users/${id}`),7});Info
Function path variables
When the path is a function, it receives the same variables that are passed to toQuery(), fn(), mutate(), or mutateAsync().
1type UpdateUserInput = {2 id: string;3 body: {4 name: string;5 };6};7 8const users = api.resource("users", {9 detail: api.get<User, string>((id) => `/users/${id}`),10 update: api.patch<User, UpdateUserInput>(({ id }) => `/users/${id}`, {11 body: ({ body }) => body,12 }),13});14 15users.detail.toQuery("user-1");16// Path function receives "user-1" and builds /users/user-1.17 18await users.update.fn({19 id: "user-1",20 body: {21 name: "Jane",22 },23});24// Path function receives the object and uses variables.id.Query keys
Generated query keys follow one stable shape.
The API name avoids collisions between different backends. The resource and endpoint names keep the key readable. Variables are appended when the endpoint uses them.
1users.list.key();2// ["main", "users", "list"]3 4users.detail.key("user-1");5// ["main", "users", "detail", "user-1"]6 7users.list.baseKey();8// ["main", "users", "list"]Invalidation
Use baseKey() when a mutation should refresh a group of related queries.
Use key(variables) when you want to refresh one exact query.
1const updateUser = useMutation({2 ...users.update.toMutation(),3 onSuccess: (updatedUser) => {4 queryClient.invalidateQueries({5 queryKey: users.detail.key(updatedUser.id),6 });7 8 queryClient.invalidateQueries({9 queryKey: users.list.baseKey(),10 });11 },12});