# TanStack Query

Widgets built from the canonical template use TanStack Query for remote data: caching, loading and error states, cancellation and invalidation. Each feature keeps its query keys and hooks in `src/features/<name>/hooks/`, on top of the functions in its `api/` layer.

Feature structure: `modyo://docs/widgets/patterns-features`. API functions and mocks: `modyo://docs/widgets/patterns-api-clients`.

---

## Provider: `src/app/providers/QueryProvider.tsx`

```tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import type { ReactNode } from 'react';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000,
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
});

interface QueryProviderProps {
  children: ReactNode;
}

export function QueryProvider({ children }: QueryProviderProps) {
  return (
    <QueryClientProvider client={queryClient}>
      {children}
      {import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
    </QueryClientProvider>
  );
}
```

`src/app/App.tsx` wraps the page with it, inside the `DContextProvider` mounted by `src/app/main.tsx`:

```tsx
  return (
    <QueryProvider>
      <ErrorBoundary>
        <DCard className="container my-md-14">
          <DCard.Body className="d-flex flex-column gap-4 p-4 p-md-14">
            {missingVariables.length > 0
              ? <MissingVariables names={missingVariables} />
              : <HomePage />}
          </DCard.Body>
        </DCard>
      </ErrorBoundary>
    </QueryProvider>
  );
```

The provider is part of the template; do not create a second `QueryClient`.

---

## Keys and hooks of a feature

From `src/features/entities/hooks/useEntities.ts`:

```ts
import {
  keepPreviousData,
  useMutation,
  useQuery,
  useQueryClient,
} from '@tanstack/react-query';

import { createEntity, getEntities } from '../api/entityApi';
import type { CreateEntityData, EntityFilters } from '../model/entity';

export const entityKeys = {
  all: ['entities'] as const,
  lists: () => [...entityKeys.all, 'list'] as const,
  list: (filters: EntityFilters) => [...entityKeys.lists(), filters] as const,
};

export function useEntities(filters: EntityFilters = {}) {
  return useQuery({
    queryKey: entityKeys.list(filters),
    queryFn: ({ signal }) => getEntities(filters, signal),
    placeholderData: keepPreviousData,
  });
}

export function useCreateEntity() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: CreateEntityData) => createEntity(data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: entityKeys.lists() }),
  });
}
```

### Keys

- Every key of a feature hangs from `<entity>Keys.all`, so the feature can be invalidated by level (`all`, `lists()`, `list(filters)`).
- The first key (`['entities']`) must be unique in the widget. When copying the reference feature, rename it with the domain.
- Filters are part of the key: each combination of filters has its own cache entry. `placeholderData: keepPreviousData` keeps showing the previous list while the new one loads.

### Queries

- `queryFn` passes TanStack Query's `signal` to the `api/` function, which forwards it to Axios. The request is cancelled when the query is no longer used.
- Hooks call `api/` (or `service/`, when the feature has one). They never import the HTTP client or `*.mock.ts` files.

### Mutations

- The mutation calls the `api/` function and, on success, invalidates the affected keys (`entityKeys.lists()`), so every list refetches.

---

## Using the hooks in `ui/`

`ui/` reads data and states from the hooks and renders them with `DDataStateWrapper` and the shared state components. From `src/features/entities/ui/EntityListScreen.tsx`:

```tsx
  const [searchQuery, setSearchQuery] = useState('');
  const search = useDebouncedValue(searchQuery, SEARCH_DEBOUNCE);

  const { data, isLoading, isError, refetch } = useEntities({ search });
  const { mutateAsync: createEntity } = useCreateEntity();
  const retry = () => {
    void refetch();
  };
```

```tsx
      <DDataStateWrapper
        isLoading={isLoading}
        isError={isError}
        data={data}
        onRetry={retry}
        renderLoading={<LoadingState variant="list" items={5} />}
        renderEmpty={<EmptyState message={t('entities.list.empty')} />}
        renderError={<ErrorState message={t('entities.list.error')} onRetry={retry} />}
      >
        {(entities) => (
          <DListGroup ariaLabel={t('entities.list.title')}>
            {entities.map((entity) => (
              <DListGroup.Item key={entity.id}>{entity.name}</DListGroup.Item>
            ))}
          </DListGroup>
        )}
      </DDataStateWrapper>
```

Loading, error and empty states: `modyo://docs/widgets/patterns-data-states`.

---

## Portals render outside the `QueryProvider`

Modals registered in `availablePortals` render next to the `App` tree, outside its `QueryProvider`. A portal component therefore does **not** call TanStack Query hooks. The component that opens it (inside the provider) passes the action in the payload:

```tsx
// ui/EntityListScreen.tsx
        <DButton
          text={t('entities.list.create')}
          iconStart="Plus"
          onClick={() => openPortal('entity-create', { onCreate: createEntity })}
        />
```

```tsx
// ui/EntityCreateModal.tsx
export type EntityCreatePayload = {
  onCreate: (data: CreateEntityData) => Promise<unknown>;
};

export type EntityPortals = {
  'entity-create': EntityCreatePayload;
};
```

The modal calls `payload.onCreate(...)` and closes itself with `closePortal()` from `useDPortalContext`. Portal registration: `modyo://docs/widgets/patterns-features` (Adding a feature).

---

## See also

- `modyo://docs/widgets/patterns-features` — feature layers
- `modyo://docs/widgets/patterns-api-clients` — `api/` functions, `AbortSignal` and mocks
- `modyo://docs/widgets/patterns-hooks` — where hooks live and local UI state
- `modyo://docs/widgets/patterns-data-states` — loading, error and empty states
