# Migrating from TanStack Query

TanStack Query (React Query) caches each query key's response on its own, so the app keeps them consistent by
invalidating keys after every mutation. Reactive Data Client [normalizes](https://dataclient.io/docs/concepts/normalization.md) responses
into [Entities](https://dataclient.io/rest/api/Entity.md): a mutation's response updates every list and detail that shows that entity, and
most invalidation code goes away.

The migration replaces query functions and keys with typed endpoints, hooks with [useSuspense()](https://dataclient.io/docs/api/useSuspense.md)
and [Controller](https://dataclient.io/docs/api/Controller.md) calls, and the `QueryClient` with [DataProvider](https://dataclient.io/docs/api/DataProvider.md).
[Steps](#steps) gives the order; [API map](#api-map) gives the replacement for each TanStack Query API.

To migrate an app from TanStack Query, install the setup skill from the project root, then read
`.agents/skills/data-client-setup/SKILL.md` and follow it:

```bash
npx skills add reactive/data-client --skill data-client-setup -y
```

## Steps {#steps}

Keep the app's tests passing after each step; they are the proof that behavior didn't change.

1. **Endpoints and schemas.** Turn each query and mutation function into an endpoint: follow the
   [REST setup](https://dataclient.io/rest.md) for the HTTP library the functions call (axios, fetch, ky), then give each endpoint a
   `schema` built from [Entities](https://dataclient.io/rest/api/Entity.md). Without a schema nothing is normalized, and you will need to keep
   every `invalidateQueries` call. Put the Entities and endpoints in one folder every feature may import (such as
   `src/resources/`), not in each feature's `api/` folder, even when the query hooks lived there: a mutation in one
   feature often updates another feature's Entity. If lint rules restrict imports between folders
   (`import/no-restricted-paths`, `eslint-plugin-boundaries`, Nx module boundaries), use a shared layer they allow.
2. **Provider.** Replace `QueryClientProvider` with `DataProvider` ([Provider](#provider)).
3. **Reads.** Replace `useQuery()` and `useSuspenseQuery()` with `useSuspense()` in the component that renders the
   data ([Reads](#reads)).
4. **Mutations.** Replace `useMutation()` with `ctrl.fetch()`, and delete the invalidation that normalization makes
   unneeded ([Mutations](#mutations)).
5. **Loaders and prefetching.** Replace `queryClient` in router loaders and hover prefetching with
   `ctrl.fetchIfStale()` ([Loaders and prefetching](#loaders)).
6. **Infinite queries.** Replace `useInfiniteQuery()` with a [Collection](https://dataclient.io/rest/api/Collection.md) and `getPage`
   ([Infinite queries](#infinite)).
7. **Auth.** Replace auth libraries built on TanStack Query, like `react-query-auth` ([Auth](#auth)).
8. **Tests.** Replace `QueryClientProvider` in test wrappers, and loading-spinner assumptions ([Tests](#tests)).
9. **Clean up.** Delete query key factories, `queryOptions()` helpers and `lib/react-query.ts`-style config. Uninstall
   `@tanstack/react-query` and `@tanstack/react-query-devtools` when no file imports them.

These steps keep the app's behavior, except where Data Client fixes it with less code: lists that showed stale data
after a mutation, refetches after a mutation, and fetches for items a list already loaded. Changes that need extra code
or change what users see, like adding optimistic updates the app did not have, are a separate, optional
[performance pass](https://dataclient.io/docs/guides/performance-pass.md). Finish and check the migration first, so you can measure each stage.

## API map {#api-map}

| TanStack Query                                                               | Data Client                                                                                                                                                                                                           |
| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `queryFn` + `queryKey`, `queryOptions()`                                     | An endpoint with a `schema`. The endpoint and its args are the key, so key factories go away                                                                                                                          |
| `useQuery()`, `useSuspenseQuery()`                                           | `useSuspense(endpoint, args)`: loading goes to the nearest `<Suspense>`, errors to the nearest error boundary, and `data` is never `undefined`                                                                        |
| `useQuery()` where the component renders its own spinner or error            | [useDLE()](https://dataclient.io/docs/api/useDLE.md): `{ data, loading, error }`                                                                                                                                      |
| `enabled: false`                                                             | `null` in place of the args: `useSuspense(endpoint, id ? { id } : null)` returns `undefined` and fetches nothing                                                                                                      |
| `select`                                                                     | Compute in render, or a [Query](https://dataclient.io/rest/api/Query.md) schema read with [useQuery()](https://dataclient.io/docs/api/useQuery.md)                                                                    |
| `useQueries()`                                                               | [useFetch()](https://dataclient.io/docs/api/useFetch.md) for each, then React 19's `use()`: they fetch in parallel. On React 18, call `useSuspense()` for each after the `useFetch()` calls; it reuses their requests |
| `staleTime`                                                                  | [dataExpiryLength](https://dataclient.io/docs/concepts/expiry-policy.md#endpointdataexpirylength) on the endpoint or base class. The default is 60 seconds (TanStack Query's is 0)                                    |
| `gcTime`                                                                     | `DataProvider`'s [gcPolicy](https://dataclient.io/docs/api/DataProvider.md#gcPolicy)                                                                                                                                  |
| `retry`                                                                      | Delete it: Data Client has no retry loop. An errored request is fetched again when a component needs it after `errorExpiryLength` (default 1 second), like TanStack Query's `retry: false`                            |
| `refetchInterval`                                                            | `pollFrequency` on the endpoint, read with [useLive()](https://dataclient.io/docs/api/useLive.md)                                                                                                                     |
| `refetchOnWindowFocus`                                                       | Delete it: Data Client doesn't refetch on window focus. On React Native with React Navigation, a screen refetches its stale data when it regains focus                                                                |
| `placeholderData: keepPreviousData`                                          | Change the args inside `startTransition()` (or [useDebounce()](https://dataclient.io/docs/api/useDebounce.md) for typed input): React keeps showing the current data while the next loads                             |
| `initialData` from a list query                                              | Delete it: while the list's data is fresh, an Entity it loaded renders on the detail page without a fetch, when the detail endpoint's schema is that Entity                                                           |
| `useMutation()`                                                              | `ctrl.fetch(endpoint, ...args)` in the event handler, from [useController()](https://dataclient.io/docs/api/useController.md)                                                                                         |
| `isPending`, `error` of a mutation                                           | [useLoading()](https://dataclient.io/docs/api/useLoading.md): `const [run, isPending, error] = useLoading(fn, deps)`                                                                                                  |
| `isSuccess`, `onSuccess`, `onError`                                          | Code after or around `await ctrl.fetch()` ([Mutations](#mutations))                                                                                                                                                   |
| `invalidateQueries()` after an update                                        | Delete it, when the response is the updated Entity                                                                                                                                                                    |
| `invalidateQueries()` after a create                                         | `ctrl.fetch(Resource.getList.push, body)` (or `unshift`); numbered pages differ ([Mutations](#mutations))                                                                                                             |
| `invalidateQueries()` after a delete                                         | Delete it: `resource().delete` (or a `schema.Invalidate` schema) removes the Entity from every list                                                                                                                   |
| `invalidateQueries()` for data the response doesn't include (counts, totals) | `ctrl.expireAll(endpoint)`: mounted components refetch                                                                                                                                                                |
| `refetchQueries()`                                                           | `ctrl.fetch(endpoint, args)`                                                                                                                                                                                          |
| `setQueryData()`                                                             | `ctrl.setResponse(endpoint, args, response)`; for Entities, `ctrl.set(Entity, args, value)`                                                                                                                           |
| `getQueryData()`                                                             | In a component, [useCache()](https://dataclient.io/docs/api/useCache.md). Elsewhere, `ctrl.get(schema, args, ctrl.getState())`                                                                                        |
| `prefetchQuery()`                                                            | `ctrl.fetchIfStale(endpoint, args)`, not awaited: a failure never rejects unhandled                                                                                                                                   |
| `ensureQueryData()`, `getQueryData() ?? fetchQuery()`                        | Cached data from `ctrl.getResponse()` when it can render, else `ctrl.fetchIfStale(endpoint, args)` ([Loaders](#loaders))                                                                                              |
| `fetchQuery()`                                                               | `await ctrl.fetchIfStale(endpoint, args)` with a `staleTime`; `ctrl.fetch(endpoint, args)` without                                                                                                                    |
| `onMutate` optimistic update and rollback                                    | [getOptimisticResponse()](https://dataclient.io/rest/guides/optimistic-updates.md) on the endpoint: Data Client rolls back on error                                                                                   |
| `useInfiniteQuery()`                                                         | A [Collection](https://dataclient.io/rest/api/Collection.md) and `ctrl.fetch(endpoint.getPage, args)` ([Infinite queries](#infinite))                                                                                 |
| `onError` on `QueryCache` or `MutationCache` (global error reporting)        | An [error reporting Manager](https://dataclient.io/docs/concepts/managers.md#error-reporting): it sees every failed fetch                                                                                             |
| `queryClient.clear()`, `removeQueries()` on logout                           | `ctrl.resetEntireStore()`                                                                                                                                                                                             |
| `QueryClientProvider`, `new QueryClient()`                                   | `DataProvider`                                                                                                                                                                                                        |
| `useQueryClient()`                                                           | `useController()`                                                                                                                                                                                                     |
| `ReactQueryDevtools`                                                         | Delete it: `DataProvider` adds [devtools](https://dataclient.io/docs/getting-started/debugging.md) in development                                                                                                     |
| `HydrationBoundary`, `dehydrate()`                                           | [Server Side Rendering](https://dataclient.io/docs/guides/ssr.md)                                                                                                                                                     |

> **Warning**
>
> Data Client's own [useQuery()](https://dataclient.io/docs/api/useQuery.md) is not TanStack Query's. It reads a schema from the store and never
> fetches. Replace TanStack Query's `useQuery()` with `useSuspense()` or `useDLE()`.

## Provider {#provider}

Put `DataProvider` at the root, outside the app's other providers and `<Suspense>` boundaries, rather than where
`QueryClientProvider` was. Its backup boundary, which shows "Uncaught Suspense" in development, catches before any
boundary above it.

```tsx title="provider.tsx"
import { DataProvider } from '@data-client/react';
import { Suspense, type ReactNode } from 'react';

export const AppProvider = ({ children }: { children: ReactNode }) => (
  <DataProvider>
    <Suspense fallback={<Loading />}>{children}</Suspense>
  </DataProvider>
);
```

`DataProvider` makes its own store, so there is no client to create. Move `QueryClient` `defaultOptions` to the base
endpoint class, as the [API map](#api-map) lists.

## Reads {#reads}

Call `useSuspense()` in the component that renders the data, and delete the per-feature `useIssues()` hook that
wrapped `useQuery()`. Two components that ask for the same endpoint and args share one fetch and one store entry, so
nothing is gained by sharing a hook, and a hook hides what the component depends on.

```ts title="Before"
export const issueKeys = {
  all: ['issues'] as const,
  list: (page: number) => [...issueKeys.all, 'list', page] as const,
  detail: (id: number) => [...issueKeys.all, 'detail', id] as const,
};

export const useIssues = (page: number) =>
  useQuery({ queryKey: issueKeys.list(page), queryFn: () => fetchIssues(page) });
```

```tsx title="Before, in IssueTable"
const { data, isLoading, isError } = useIssues(page);
if (isLoading) return <TableSkeleton />;
if (isError) return <ErrorBanner />;
return <Table rows={data?.results ?? []} />;
```

```tsx title="After"
import { useSuspense } from '@data-client/react';
import { IssueResource } from './resources/Issue';

export function IssueTable({ page }: { page: number }) {
  const { results: issues, pagination } = useSuspense(IssueResource.getList, {
    page,
  });
  return (
    <table>
      <caption>
        Page {pagination.page} of {pagination.pageCount}
      </caption>
      <tbody>
        {issues.map(issue => (
          <tr key={issue.id}>
            <td>{issue.title}</td>
            <td>{issue.state}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
```

The `isLoading` branch moves to a `<Suspense>` fallback, and the `isError` branch to an error boundary; an
[AsyncBoundary](https://dataclient.io/docs/api/AsyncBoundary.md) is both. Keep the app's own skeleton and error banner as their fallbacks. The
`?? []` guard goes away, because `useSuspense()` returns only once data is there.

Two `useSuspense()` calls in one component load one after the other. When neither needs the other's data, start both
with `useFetch()` and read them with `use()` ([parallel data loading](https://dataclient.io/docs/api/useFetch.md#parallel-data-loading)). On
React 18, which has no `use()`, read them with `useSuspense()` after both `useFetch()` calls.

### Envelope responses

When the API wraps responses in an envelope (an outer object that holds the data next to metadata), like
`{ "results": [...], "pagination": {...} }`, make the envelope the schema, so components keep reading `pagination`:

```ts title="resources/Issue.ts"
import { Entity, resource } from '@data-client/rest';

export class Issue extends Entity {
  id = 0;
  title = '';
  state: 'open' | 'closed' = 'open';
  assignee = '';

  static key = 'Issue';
}

interface Pagination {
  page: number;
  pageCount: number;
}

export const IssueResource = resource({
  path: '/issues/:id',
  searchParams: {} as { page?: number },
  schema: Issue,
}).extend(Base => ({
  getList: Base.getList.extend({
    schema: { results: [Issue], pagination: {} as Pagination },
  }),
  // a new issue shifts every numbered page, so this POST joins no list: callers expire it
  create: Base.getList.push.extend({ schema: Issue }),
}));
```

`searchParams` types the list's `page` argument. `create` reuses the list's `POST`, with the plain `Issue` schema in
place of the list's Collection; [Mutations](#mutations) says when to use it. When single items
come wrapped too, like `{ "data": {...} }`, extend `get` the same way: `Base.get.extend({ schema: { data: Issue } })`.

## Mutations {#mutations}

Call `ctrl.fetch()` where the app called `mutate()`. What `onSuccess` did goes after the `await`; `onError` goes in
a `catch`. Track pending and error state with `useLoading()`.

```ts title="Before"
export const useCloseIssue = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => patchIssue(id, { state: 'closed' }),
    onSuccess: issue => {
      queryClient.invalidateQueries({ queryKey: issueKeys.detail(issue.id) });
      toast(`Closed #${issue.id}`);
    },
    onError: () => toast('Could not close the issue'),
  });
};
```

```tsx title="After"
import { useController, useLoading } from '@data-client/react';
import { IssueResource } from './resources/Issue';

export function CloseIssueButton({ id }: { id: number }) {
  const ctrl = useController();
  const [close, isPending] = useLoading(async () => {
    try {
      await ctrl.fetch(IssueResource.partialUpdate, { id }, { state: 'closed' });
      toast(`Closed #${id}`);
    } catch {
      toast('Could not close the issue');
    }
  }, [ctrl, id]);
  return (
    <button onClick={close} disabled={isPending}>
      Close issue
    </button>
  );
}
```

The `invalidateQueries()` call is gone: the response is the updated `Issue`, so the table and the detail page both
show it closed. TanStack Query apps usually invalidate the detail key but not every list key, so lists show stale
data until they expire; after the migration they don't.

Decide what to do with each `invalidateQueries()` and `refetchQueries()` call from the response (more examples in
[mutations](https://dataclient.io/docs/getting-started/mutations.md)):

- **Response is the changed Entity** (update, partial update): delete the call, unless the change moves the Entity
  between filtered or sorted lists. Closing an issue updates it everywhere, but doesn't remove it from a cached
  `?state=open` list or add it to a `?state=closed` one; keep those right with `ctrl.expireAll(Resource.getList)`.
- **Create**: fetch the list's `push` (or `unshift`) endpoint instead of the plain `POST`, and the new Entity joins every
  matching list. This needs a [Collection](https://dataclient.io/rest/api/Collection.md) in the list's schema: `resource()` has one by default,
  and an envelope needs it inside, like `results: new Collection([Issue])`. For lists split into
  numbered pages, where a new item shifts every page, add a plain `POST` endpoint (`create` in the
  [envelope example](#envelope-responses): `Base.getList.push.extend({ schema: Issue })`), then call
  `ctrl.expireAll(Resource.getList)`.
- **Delete**: `resource().delete` removes the Entity from every list. For a custom endpoint, use
  `schema: new schema.Invalidate(MyEntity)`. For lists split into numbered pages, also call
  `ctrl.expireAll(Resource.getList)`: the server's later items move up a page, which the cached pages can't know.
- **Data the response doesn't include** (a count, another resource's totals): `ctrl.expireAll(endpoint)`, or return
  it in the response ([side effects](https://dataclient.io/rest/guides/side-effects.md)).

### Success state

`useLoading()` has no `isSuccess`, and the function it returns never rejects: it stores the error instead. So close a
form or dialog after `await ctrl.fetch()` inside the function you pass to `useLoading()`, not after calling the
returned function. To keep a success flag:

```ts title="useMutate.ts"
import { useLoading } from '@data-client/react';
import { useState } from 'react';

export function useMutate<A extends unknown[]>(
  mutate: (...args: A) => Promise<unknown>,
  deps: readonly unknown[],
) {
  const [isDone, setIsDone] = useState(false);
  const [run, isPending, error] = useLoading(async (...args: A) => {
    setIsDone(false);
    await mutate(...args);
    setIsDone(true);
  }, deps);
  return { run, isPending, error, isDone };
}
```

## Loaders and prefetching {#loaders}

Router loaders that receive the `queryClient` receive the Controller instead. `useController()` returns the same
Controller on every render, so it is safe to create the router from it.

```ts title="Before"
export const issueLoader =
  (queryClient: QueryClient) =>
  ({ params }: LoaderFunctionArgs) =>
    queryClient.ensureQueryData({
      queryKey: issueKeys.detail(Number(params.issueId)),
      queryFn: () => fetchIssue(Number(params.issueId)),
    });
```

```ts title="After"
import { ExpiryStatus, type Controller } from '@data-client/react';
import { IssueResource } from './resources/Issue';

export const issueLoader =
  (ctrl: Controller) =>
  ({ params }: { params: { issueId?: string } }) => {
    const args = { id: Number(params.issueId) };
    const { data, expiryStatus } = ctrl.getResponse(
      IssueResource.get,
      args,
      ctrl.getState(),
    );
    // fetches only when missing or stale
    const fetched = ctrl.fetchIfStale(IssueResource.get, args);
    // like ensureQueryData(): cached data, even stale, navigates now; a miss waits for the fetch
    return expiryStatus === ExpiryStatus.Valid ? data : fetched;
  };
```

`fetchIfStale()` fetches only when the data is missing or stale, and always returns a Promise. Left unawaited, it works
like `prefetchQuery()`: a failure never rejects unhandled, and is stored for components to show. Use it for hover or
focus prefetching too: `onMouseEnter={() => ctrl.fetchIfStale(IssueResource.get, { id })}`. Awaited, it works like
`fetchQuery()` with a `staleTime`: it resolves the data, waiting for the refetch when cached data is stale, or rejects
with the error. Use the awaited form where the loader used `fetchQuery()`, and the pattern above where it used
`ensureQueryData()` or `getQueryData() ?? fetchQuery()`. [Route loaders](https://dataclient.io/docs/api/Controller.md#fetchIfStale-loaders)
shows loaders that don't make navigation wait. Load several endpoints the way the loader did before;
letting the page show before secondary data arrives belongs to the [performance pass](https://dataclient.io/docs/guides/performance-pass.md#loaders).

## Infinite queries {#infinite}

`useInfiniteQuery()` keeps an array of pages. Data Client keeps one list: a [Collection](https://dataclient.io/rest/api/Collection.md) that each
new page appends to. Set `paginationField` on the endpoint to get its `getPage` endpoint.

```ts title="resources/Note.ts"
import { Collection, Entity, RestEndpoint } from '@data-client/rest';

export class Note extends Entity {
  id = 0;
  text = '';
  author = '';

  static key = 'Note';
}

// every page of one issue's notes shares one list
const issueNotes = new Collection([Note], {
  argsKey: ({ issueId }: { issueId: number }) => ({ issueId }),
});

export const getNotes = new RestEndpoint({
  path: '/issues/:issueId/notes',
  searchParams: {} as { page?: number },
  schema: { results: issueNotes, nextPage: 0 as number | null },
  paginationField: 'page',
});

export const addNote = new RestEndpoint({
  path: '/issues/:issueId/notes',
  method: 'POST',
  body: {} as { text: string },
  schema: issueNotes.push,
});
```

`argsKey` leaves out `page`, so every page and the `push` endpoint find the same list. A new note appears without
invalidating anything.

```tsx title="IssueNotes.tsx"
import { useController, useLoading, useSuspense } from '@data-client/react';
import { getNotes } from './resources/Note';

export function IssueNotes({ issueId }: { issueId: number }) {
  const { results: notes, nextPage } = useSuspense(getNotes, { issueId });
  const ctrl = useController();
  const [loadMore, isLoadingMore] = useLoading(
    async (page: number) => ctrl.fetch(getNotes.getPage, { issueId, page }),
    [ctrl, issueId],
  );
  return (
    <>
      <ul>
        {notes.map(note => (
          <li key={note.id}>
            {note.author}: {note.text}
          </li>
        ))}
      </ul>
      {nextPage !== null && (
        <button onClick={() => loadMore(nextPage)} disabled={isLoadingMore}>
          Show older notes
        </button>
      )}
    </>
  );
}
```

`pages.flatMap()` goes away. What `getNextPageParam` computed and `hasNextPage` reported come from the response
(`nextPage` here), which `getPage` updates along with the list. `isFetchingNextPage` is `useLoading()`'s pending flag.
For cursors, see [pagination](https://dataclient.io/rest/guides/pagination.md).

## Auth {#auth}

Libraries like `react-query-auth` give `useUser()`, `useLogin()`, `useLogout()` and `AuthLoader` on top of TanStack
Query. Rebuild them from endpoints:

```ts title="session.ts"
import { useController, useLoading, useSuspense } from '@data-client/react';
import { Entity, RestEndpoint } from '@data-client/rest';

class Account extends Entity {
  id = '';
  displayName = '';

  static key = 'Account';
}

const getSession = new RestEndpoint({
  path: '/session',
  schema: { account: Account },
});
const signIn = new RestEndpoint({
  path: '/session',
  method: 'POST',
  body: {} as { username: string; password: string },
  schema: { account: Account, token: '' },
});
const signOut = new RestEndpoint({ path: '/session', method: 'DELETE' });

export const useAccount = () => useSuspense(getSession).account;

export const useSignIn = (onSuccess?: () => void) => {
  const ctrl = useController();
  return useLoading(
    async (body: { username: string; password: string }) => {
      const { account } = await ctrl.fetch(signIn, body);
      // the signed-in account becomes the current one without refetching
      await ctrl.setResponse(getSession, { account });
      onSuccess?.();
    },
    [ctrl, onSuccess],
  );
};

export const useSignOut = (onSuccess?: () => void) => {
  const ctrl = useController();
  return useLoading(async () => {
    await ctrl.fetch(signOut);
    await ctrl.resetEntireStore();
    onSuccess?.();
  }, [ctrl, onSuccess]);
};
```

For sign-up, copy `useSignIn()` as `useSignUp()` with the sign-up endpoint and its body type. `AuthLoader` goes away: `useAccount()` suspends
to the app's `<Suspense>` boundary until the session loads. These hooks wrap actions, not a data binding, so they are
worth keeping as hooks.

Call sites change shape:

- `useUser().data` becomes the value itself: `useAccount()`.
- `useLogin({ onSuccess }).mutate(values)` becomes `const [signIn, isPending] = useSignIn(onSuccess)`, then
  `signIn(values)`.

`useAccount()` needs `/session` to answer a signed-out visitor with no account, as `react-query-auth`'s `userFn` returns
`null`. Then signed-out pages render, and the refetch after `resetEntireStore()` shows the signed-out state. If the API
answers 401 instead, the error reaches the nearest error boundary, so turn that status into a signed-out response:

```ts title="getSession.ts"
import { Entity, NetworkError, RestEndpoint } from '@data-client/rest';

class Account extends Entity {
  id = '';
  displayName = '';

  static key = 'Account';
}

export const getSession = new RestEndpoint({
  path: '/session',
  schema: { account: Account },
  async fetchResponse(input: RequestInfo, init: RequestInit) {
    const response = await fetch(input, init);
    if (response.status === 401) {
      // parseResponse() reads JSON only when the Content-Type says so
      return new Response(JSON.stringify({ account: null }), {
        headers: { 'Content-Type': 'application/json' },
      });
    }
    if (!response.ok) throw new NetworkError(response);
    return response;
  },
});
```

To sign out on any other 401 response, add [LogoutManager](https://dataclient.io/docs/api/LogoutManager.md); for token storage, see
[authentication](https://dataclient.io/rest/guides/auth.md).

## Tests {#tests}

- Replace `QueryClientProvider` (and the per-test `new QueryClient()`) in test wrappers with `DataProvider`, with
  `<Suspense>` inside it. Each `DataProvider` mount starts with an empty store.

- Helpers that wait for a spinner to disappear fail when the data is already in the store, because then nothing
  suspends. Wait only when a spinner is present:

  ```ts title="test-utils.ts"
  import { screen, waitForElementToBeRemoved } from '@testing-library/react';

  const loadingElements = () => screen.queryAllByTestId(/loading/i);

  export const waitForLoadingToFinish = async () => {
    if (loadingElements().length)
      await waitForElementToBeRemoved(loadingElements);
  };
  ```

- Mock servers (MSW, `nock`) keep working unchanged. To render from fixtures without a server, use
  [MockResolver](https://dataclient.io/docs/api/MockResolver.md).

- Assertions on query keys or `queryClient` state go away; assert on what renders.

## Check the migration {#check}

- No file imports `@tanstack/react-query`, and no `queryKey`, `queryOptions` or `useQueryClient` remains.
- Every endpoint that returns Entities has a `schema`.
- The linter passes, including its import-boundary rules, and no feature folder defines an Entity.
- Each `<Suspense>` or `AsyncBoundary` that catches a `useSuspense()` is inside `DataProvider`.
- The type checker, unit tests and end-to-end tests pass.
- Opening an item from a freshly loaded list makes no request for that item, when the list returns the full item.
- After a mutation, every page showing that Entity shows the change without a reload. A test that edits an item on
  its detail page, then goes back to the list, proves it.
