Skip to Content
Effetch Query
React

Read a query

Show a query's result in a component with useQuery.

You've defined a query and want a component to show it. useQuery reads the query and returns its AsyncResult: loading, the value, or an error typed as the query defines it. This page shows how to render each state, when the hook fetches, and how to read part of a value or several queries at once.

The examples import client.ts and todos.ts from Getting started.

Provide the client

Every hook and component from @monarcode/effetch-query/react reads the query client of the nearest QueryProvider, so put one above them:

import type {  } from "react";

import {  } from "@monarcode/effetch-query/react";

import {  } from "./client.js";

export function ({  }: { readonly :  }) {
  return < ={}>{}</>;
}

The provider never disposes a client you pass it. It also shares the client's registry, the store that holds the cache, with @effect/atom-react, so atom-react's own hooks read the same cache: see Atoms. Outside a provider, the hooks throw a MissingQueryProviderError.

To use the client itself in a component, such as to run an Effect from an event handler with client.runPromise, call useQueryClient(): see Read and write outside Effect. For a client the provider makes, and makes again when the signed-in account changes, see Sign out and switch accounts.

Render each state

Match on the result to show each state:

import * as  from "effect/reactivity/AsyncResult";

import {  } from "@monarcode/effetch-query/react";

import {  } from "./todos.js";

export function ({  }: { readonly : number }) {
  const  = (({ : {  } }));

  return .(, {
    : () => <>Loading…</>,
    : () =>
      . === "HttpError" && . === 404 ? (
        <>There's no todo {}.</>
      ) : (
        <>Couldn't load the todo: {.}</>
      ),
    : () => <>Something went wrong.</>,
    : ({ ,  }) => (
      < ={{ :  ? 0.5 : 1 }}>{.}</>
    ),
  });
}

An AsyncResult is Initial before there's a value, Success with the value, or Failure with the full Cause. matchWithError splits a failure in two: onError gets the typed error, here todo's NetworkError | DecodeError | HttpError, and onDefect gets a defect, an unexpected error such as a bug, which the query's type doesn't list.

Rather than checking a status in every component, an endpoint can turn a 404 into an error of your own, such as TodoNotFound: see Query errors.

When it fetches

Every component that reads the same query shares one fetch. When the component mounts, and when its query changes, useQuery refetches the query if it's stale (refetchOnMount) or failed (retryOnMount): see The mount policy. Both are on by default. While the component is mounted, the query also refetches on focus, on reconnect and on its refetchInterval, as its options say: see Freshness and refetching.

In a server render, useQuery reads only the cache. It never starts a fetch there, and the mount refetch doesn't run. These readers do fetch in a server render: useSuspenseQuery and useSuspenseInfiniteQuery, for streaming, as Suspense and error boundaries shows, and an atom derived from a query, unless you give it a server value, as Atoms shows.

Tell a first load from a refetch

waiting is true while the query fetches, and what it's attached to tells you which fetch it is:

  • A first load is a waiting Initial.
  • A refetch shows what the query had, a Success or a Failure, with waiting true.

So AsyncResult.isInitial(result) tells a first load from a refetch. To handle the two alike, use AsyncResult.matchWithWaiting, or onInitialOrWaiting on AsyncResult.builder(result), which builds a match one case at a time.

A refetch that fails after a success gives a Failure whose previousSuccess holds the last value. matchWithError sends it to onError, so the example above replaces the title with the error. To keep showing the title, read previousSuccess from onError's second argument, or read the query with useQueryState, whose data keeps the last value: see Read a query as an object.

Keep the last value while the next loads

When a component switches to a query that has no value yet, such as the next todo, it shows Initial. Pass keepPrevious to show the last value instead:

import * as  from "effect/reactivity/AsyncResult";

import {  } from "@monarcode/effetch-query/react";

import {  } from "./todos.js";

export function ({  }: { readonly : number }) {
  const  = (({ : {  } }), { : true });
  const  = .(
    .(, () => .),
    () => "Loading…",
  );
  return < ={{ : . ? 0.5 : 1 }}>{}</>;
}

The hook shows the last success it showed, as a waiting Success, until the next query's value or failure arrives: TanStack Query's placeholderData: keepPreviousData. Only a query's own value is kept, not a placeholder. A failure shows as it is, and a null query still reads Initial. useQueryState's isPlaceholder is true for the kept value: see Read a query as an object.

Read nothing until you're ready

When a query needs a value you don't have yet, such as the selected todo's ID, pass null until you have it:

import * as  from "effect/reactivity/AsyncResult";

import {  } from "@monarcode/effetch-query/react";

import {  } from "./todos.js";

export function ({  }: { readonly : number | null }) {
  const  = ( === null ? null : ({ : {  } }));

  if ( === null) {
    return <>Pick a todo.</>;
  }
  return .()
    .(() => <>{.}</>)
    .(() => <>Couldn't load the todo.</>)
    .(() => <>Loading…</>);
}

useQuery(null) fetches nothing and returns an Initial that isn't waiting: TanStack Query's enabled: false. Check for null after the hook, since a component can't skip a hook. Matched on its own, that Initial would show "Loading…" forever.

Select part of a value

A component that shows only how many todos are open shouldn't re-render when a title changes. select derives what the component shows from the query's value, and the component re-renders only when that changes:

import * as  from "effect/reactivity/AsyncResult";

import {  } from "@monarcode/effetch-query/react";

import {  } from "./todos.js";

export function () {
  const  = ((), {
    : () => .(() => !.).,
  });
  return <>{.(, () => 0)} open</>;
}

The component re-renders when the selection changes, or when a fetch starts or ends. Other changes to the value don't re-render it. Selections are compared by content (Equal.equals), so a new array with the same items counts as unchanged, and the hook keeps the result it showed. An inline function runs on every render; for a costly selection, define it outside the component or with useCallback. When several components need the same derived value, share one atom instead: see Atoms.

The cache keeps the whole value, so other components that read the query see it unchanged, and the query refetches on mount, focus and its interval as it does without select. A failure's previous success is selected too, and with keepPrevious, the last selection shown is kept.

useQuery, useQueryState and useSuspenseQuery take select; useQueries and useInfiniteQuery don't. Their options' types are UseQuerySelectOptions, for the first two, and UseSuspenseQueryOptions.

Read several queries

When a component reads a list of queries whose length changes, such as one per selected todo, use useQueries. It returns their results in the same order, and AsyncResult.all combines them into one:

import * as  from "effect/reactivity/AsyncResult";

import {  } from "@monarcode/effetch-query/react";

import {  } from "./todos.js";

export function ({
  ,
}: {
  readonly : <number>;
}) {
  const  = .(
    (.(() => ({ : {  } }))),
  );

  return .()
    .(() => (
      <>
        {.(() => (
          < ={.}>{.}</>
        ))}
      </>
    ))
    .(() => <>Couldn't load them</>)
    .(() => <>Loading…</>);
}

AsyncResult.all returns the first result, in list order, that isn't a success. So one failed query fails the list, and one still loading shows "Loading…". When every result is a success, it returns a Success of all the values, waiting while any of them refetches.

A few details:

  • Each query is refetched when it joins the list if it's stale or failed, as useQuery does on mount: the mount policy.
  • A null entry reads Initial.
  • A query listed twice is read once, and shows in both places.
  • A tuple of queries gives a tuple of results, each typed by its query.
  • The array keeps its identity while every result in it does, so it can be a dependency of useMemo.

Its options (UseQueriesOptions) take only paused: see Pause screens you can't see. As with useQuery, a server render reads only the cache. To read each query's status, data and error as fields, use useQueriesState: see Read several queries.

Other hooks and components

The rest of @monarcode/effetch-query/react is covered with the task it's for:

What's next

On this page