|
1 | 1 | --- |
2 | 2 | title: Client API |
3 | 3 | sidebar_position: 10 |
| 4 | +hide_table_of_contents: true |
4 | 5 | --- |
5 | 6 |
|
6 | | -Work in progress. This page is not finished yet. |
| 7 | +The Client API provides imperative methods, similar to how QueryClient and QueryCache can be used in Tanstack Query. |
| 8 | +It can be accessed via [`builder.client`](./builder#client) in the `QueryBuilder` instance. Available methods are: |
| 9 | + |
| 10 | +```ts |
| 11 | +ensureData(vars, queryOptions): Promise<Data>; |
| 12 | +ensureInfiniteData(vars, paginationOptions): Promise<InfiniteData>; |
| 13 | +refetch(vars, queryFilters, refetchOptions): Promise<void>; |
| 14 | +fetch(vars, queryOptions): Promise<Data>; |
| 15 | +fetchInfinite(vars, queryOptions): Promise<InfiniteData>; |
| 16 | +isFetching(vars, queryFilters): number; |
| 17 | +prefetch(vars, queryOptions): Promise<Data>; |
| 18 | +prefetchInfinite(vars, paginationOptions): Promise<InfiniteData>; |
| 19 | +reset(vars, queryFilters, resetOptions): Promise<void>; |
| 20 | +remove(vars, queryFilters): void; |
| 21 | +cancel(vars, queryFilters, cancelOptions): Promise<void>; |
| 22 | +invalidate(vars, queryFilters, invalidateOptions): Promise<void>; |
| 23 | +getData(vars, queryFilters): Data | undefined; |
| 24 | +setData(vars, updater, setDataOptions): Data | undefined; |
| 25 | +getState(vars): QueryState; |
| 26 | +getMutation(vars, mutationFilters): Mutation; |
| 27 | +isMutating(vars, mutationFilters): number; |
| 28 | +mutate(vars, mutationOptions): Promise<Data>; |
| 29 | +``` |
| 30 | + |
| 31 | +The main use case for these methods is to manipulate the cache outside of React components. |
| 32 | +For example, you can use `ensureData` in a router before the route is loaded, |
| 33 | +to ensure that the data for a specific article is in the cache, and if not, fetch it from the server. |
| 34 | + |
| 35 | +Most of these methods correspond to the methods in [`QueryClient`](https://tanstack.com/query/latest/docs/reference/QueryClient) of Tanstack Query. For example, `ensureData` is similar to `ensureQueryData`, and `refetch` is similar to `refetchQueries`. |
| 36 | +The main difference is that these methods are pre-populated with the variables in the builder, so you don't need to pass them again. For example, suppose we have a builder like this: |
| 37 | + |
| 38 | +```ts |
| 39 | +const articlesQuery = builder.withPath("/articles/:id").withData<ArticleData>(); |
| 40 | +``` |
| 41 | + |
| 42 | +We can fetch the data for a specific article imperatively like this: |
| 43 | + |
| 44 | +```ts |
| 45 | +const article = await articlesQuery.client.fetch({ params: { id: 1 } }); |
| 46 | +``` |
0 commit comments