Claude Skills Collection Logo
langgenius-dify

frontend-data-fetching

Use when writing, migrating, or reviewing frontend API calls, TanStack Query hooks (useQuery, useSuspenseQuery, useInfiniteQuery, useMutation), queryOptions/infiniteOptions, consoleQuery/consoleClient, webAppQuery/webAppClient, marketplaceQuery, cache policies, query invalidation, prefetching/hydration, or SSE streaming under web/. Do not use for backend api/ work, pure UI or component-ownership decisions without data/cache boundaries, Vitest/RTL test strategy alone (use frontend-testing), or E2E Cucumber/Playwright tests.
étoiles162261
forks25627
observateurs858
mise à jour2026-12-02 04:14:03

Frontend Data Fetching

Single entry point for Web data fetching, mutations, cache policies, invalidation, runtime defaults, and error toasts. Read Console service, Toast policy, Repository tooling, and Component data for domain-specific rules without duplicating them here.

Client And Transport Selection

SurfaceQuery & Key FactoryImperative / Stream ClientNotes
Console (web/service/console)consoleQueryconsoleClientShares policies in web/service/console/policies/ and background domain invalidation
WebApp (web/service/webapp)webAppQuerywebAppClientPass context (address / authSession) so WebApp query scopes keys automatically
Marketplace (web/service/marketplace)marketplaceQuerymarketplaceClientUses createTanstackQueryUtils; observe dify/marketplace-boundary
SSE streams (web/service/event-stream)—streamEvents / streamGeneratorEventsWrap a generated client call; pass isPublicAPI: true for public WebApp streams
  • Never add handwritten REST helpers (fetch, XMLHttpRequest, legacy get/post/ssePost), HTTP client value imports (Axios, Ky, Undici), handwritten DTO mirrors, or direct edits to generated contracts (@dify/contracts/*). Fix backend schemas and regenerate contracts instead.
  • For WebApp queries, let withWebAppQueryScope append context.address and context.authSession; do not hand-build scoped key arrays.
// ✅ Scoped WebApp query via context (key prefix preserved for invalidation)
const profile = useQuery(
  webAppQuery.account.profile.get.queryOptions({
    context: { authSession },
    meta: { errorToast: false },
  }),
)

// ❌ Hand-concatenating queryKey arrays
const profile = useQuery(
  webAppQuery.account.profile.get.queryOptions({
    queryKey: [...webAppQuery.account.profile.get.queryKey(), authSession],
    context: { authSession },
  }),
)
// ✅ SSE streaming through event-stream + generated client
streamEvents(
  (options) =>
    consoleClient.workspaces.current.skills.bySkillId.assist.messages.post(
      { params: { skill_id: skillId }, body },
      options,
    ),
  { onData, onError, onCompleted, getAbortController },
)

Queries, skipToken, And SSR Prefetch

  • Options factories over pass-through hooks: Pass consoleQuery.*.queryOptions(...) or infiniteOptions(...) directly to useQuery, useSuspenseQuery, useInfiniteQuery, useSuspenseInfiniteQuery, or atomWithQuery. Extract an options helper only when composing query policy (pagination cursors, shared select, freshness, or retry); do not add thin useGet* forwarding hooks.
  • Conditional queries: Branch the entire input with skipToken when required arguments are absent. Add enabled only for an independent condition, never by coercing missing IDs to '' or placing skipToken inside a partial payload. Skipped options carry a dedicated key and stay disabled even if defaults set enabled: true; never pass skipToken options to queryClient.query().
  • RSC / Layout prefetch & hydration: Routes and layouts own prefetching via getQueryClient() (QueryClient factory), queryClient.query(...) (not deprecated fetchQuery / prefetchQuery / ensureQueryData), and <HydrationBoundary state={dehydrate(queryClient)}> around matching-key client consumers. See Component data for SSR auth gates, Jotai atomWithQuery, and workspace-switch isolation.
// ✅ Branch whole input with skipToken; add enabled only for independent flags
const precheckQuery = useQuery(
  consoleQuery.enterprise.appDeploy.deploymentService.precheckWorkflowDeployment.queryOptions({
    input: appId ? { params: { app_id: appId, workflow_id: workflowId } } : skipToken,
    retry: false,
  }),
)

// ❌ Placeholder empty string + enabled, or thin pass-through wrapper hook
const useAppDetail = (appId?: string) =>
  useQuery(
    consoleQuery.apps.byAppId.get.queryOptions({
      input: { params: { app_id: appId ?? '' } },
      enabled: Boolean(appId),
    }),
  )

Type Inference First

Enforced by dify/no-query-data-type-parameters:

  • Never pass explicit generic type parameters (<T>) to useQuery, useSuspenseQuery, useInfiniteQuery, useSuspenseInfiniteQuery, useMutation, queryClient.getQueryData, or queryClient.setQueryData (including aliases, ReactQuery.*, and context.client.*). Pass DataTag-typed keys/options from consoleQuery, webAppQuery, marketplaceQuery, or queryOptions().
  • Multi-query prefix boundary: setQueriesData and getQueriesData are excluded because partial prefix keys (consoleQuery.datasets.get.key({ type: 'query' })) have no single DataTag. Type their updater parameter ((list: DatasetListResponse | undefined) => ...) or pass <T> to setQueriesData<T>. Only suppress dify/no-query-data-type-parameters inline with a concrete reason when a getQueryData/setQueryData key is genuinely untagged.
// ✅ Inferred from DataTag-typed options and queryKey
const { data } = useQuery(
  consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),
)
const cached = queryClient.getQueryData(
  consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: appId } } }),
)

// ✅ Multi-query prefix write (excluded from rule)
queryClient.setQueriesData<DatasetListResponse>(
  { queryKey: consoleQuery.datasets.get.key({ type: 'query' }) },
  (list) => list,
)

// ❌ Explicit call-site generics fail dify/no-query-data-type-parameters
const { data } = useQuery<AppDetailWithSite>(
  consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),
)
const cached = queryClient.getQueryData<AppDetailWithSite>(queryKey)

Mutation Policies And Invalidation

Callback Composition

Both consoleQuery and webAppQuery wrap createPolicyQueryUtils (Mutation policies), so policy onMutate, onSuccess, onError, and onSettled callbacks run alongside caller callbacks passed to mutationOptions(...). Enforced by dify/no-mutation-policy-bypass:

  • Pass caller callbacks to mutationOptions({ onSuccess }), never by spreading ...mutationOptions() into useMutation and overwriting callbacks, and never call options.onSuccess?.(...) manually.
  • Keep cache updates out of mutate(vars, { onSuccess }), which skips if the component unmounts.
// ✅ Composes caller UI effects with the shared cache policy
const saveProfile = useMutation(
  consoleQuery.account.profile.patch.mutationOptions({
    onSuccess: () => {
      onSaved()
    },
  }),
)

// ❌ Spreading and overriding replaces the policy (dify/no-mutation-policy-bypass)
const saveProfile = useMutation({
  ...consoleQuery.account.profile.patch.mutationOptions(),
  onSuccess: () => {
    onSaved()
  },
})

Safe Policy Invalidation

Enforced by dify/prefer-invalidate-query-keys across web/ (excluding tests, mocks, stories, web/service/query-invalidation.ts, and web/service/console/mutation-invalidation.ts):

  • Never call client.invalidateQueries(...) directly (or via destructured alias); use invalidateQueryKeys(client, [key], options?) (Query invalidation), which cancels in-flight first loads and unobserved fetches first so pre-write responses cannot overwrite writes.
  • Pass supported options (exact, predicate, refetchType, cancelRefetch, throwOnError) to invalidateQueryKeys (refetchType: 'none' and cancelRefetch: false preserve in-flight fetches without cancelling them); rare unsupported filter options require // oxlint-disable-next-line dify/prefer-invalidate-query-keys -- <reason>.
  • Before direct cache writes (setQueryData, setQueriesData), await client.cancelQueries(...) if client.isFetching(...) matches those keys.
// ✅ Policy invalidation via invalidateQueryKeys
onSuccess: (_data, _variables, _result, { client }) =>
  invalidateQueryKeys(client, [consoleQuery.apps.get.key()])

// ❌ Bare invalidateQueries in policies (dify/prefer-invalidate-query-keys)
onSuccess: (_data, _variables, _result, { client }) =>
  client.invalidateQueries({ queryKey: consoleQuery.apps.get.key() })

Where Invalidation Lives

  1. Procedure policy (web/service/console/policies/<domain>.ts or WebApp query): Write a policy only when callers must await the primary source (e.g., reopening an edit form immediately) or write the response directly into cache (e.g., revealing a one-time secret). For optimistic writes, cancel queries first and settle only when client.isMutating({ mutationKey }) === 1.
  2. Automatic domain fallback for consoleQuery (Mutation invalidation + Invalidation policies): Every successful console write refreshes active queries of its own domain in the background once sibling domain mutations settle, and removes/skips deleted by<Id>.delete entity queries.
    • Cross-domain impact -> declare meta: { alsoInvalidate: ['...'] }.
    • Changes no cached data or owner reconciles cache (e.g., autosave) -> set meta: { invalidate: false } (or a predicate (variables) => boolean).
    • Read sent as POST (preview, estimate, validate, test, download) -> list in READ_ONLY_POSTS (meta: { invalidate: false, readOnly: true }) so it neither refreshes nor delays sibling writes.
    • Query kept current by its own stream/owner -> set meta: { invalidateAfterWrites: false } on its queryOptions policy.
    • Covered by web/service/console/__tests__/mutation-coverage.spec.ts. (webAppQuery and marketplaceQuery do not use the console fallback and rely on explicit policies.)
  3. Call-site invalidation: Only for user-driven refresh/retry buttons, error recovery not handled by a policy, or non-mutation events (SSE completion, async job updates).

Runtime And Error Toast Contract

  • Freshness defaults (QueryClient factory): Default staleTime is 5 minutes. Put procedure-wide overrides (staleTime: 0, gcTime: 0, staleTime: Infinity, refetchOnMount) in Freshness policies instead of repeating them at call sites; override at a call site only when that screen differs.
  • Microtask notification scheduler: In non-test browser environments (NODE_ENV !== 'test'), getQueryClient() configures notifyManager.setScheduler(queueMicrotask) so form resets and immediate cache reads do not flash a frame of stale values; tests retain the default macrotask scheduler to avoid act() noise. Server requests get a fresh QueryClient and dehydrate pending queries with errors unredacted.
  • Global error toasts (Error toasts, Toast policy): QueryCache and MutationCache report request errors once; the transport layer shows no toasts.
    • Failed queries auto-toast only when meta.errorMessage is set or the error is explained by requestErrors / the server, deduplicated per query + message for 10 seconds. Set meta: { errorToast: false } when the component renders its own error boundary or inline error.
    • Failed mutations auto-toast once; set meta: { errorMessage } for fallback text on uncataloged codes, or meta: { errorToast: false } when the form/flow presents the failure itself. Never add a duplicate toast in onError or catch.
    • Direct imperative calls (consoleClient / webAppClient outside Query) have no automatic toast: prefer useMutation, or report caught failures via reportRequestError(error, fallback).