# Read a query as an object (https://effetch-query.monarcode.dev/docs/react/as-object)

If you'd rather check fields than match on an `AsyncResult`, as you would
with TanStack Query's `useQuery`, read the query with `useQueryState`. It
fetches and takes options as `useQuery` does, `select`, `keepPrevious` and
`paused` included, and returns `status`, `data`, `error`, `isFetching`,
`refetch` and a few more fields. This page shows how to read them, where
they differ from TanStack Query's, and the hooks that return the same
object for Suspense, infinite queries and lists of queries.

The examples import `todos.ts` from [Getting started](https://effetch-query.monarcode.dev/docs/getting-started).

## Check the status, then read the fields

`status` narrows `data` and `error`, so check it first:

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

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

export function TodoTitle({ id }: { readonly id: number }) {
  const state = useQueryState(todo({ params: { id } }));

  if (state.status === "pending") {
    return <p>Loading…</p>;
  }
  if (state.status === "failure") {
    return (
      <button onClick={() => void state.refetch()}>
        Couldn't load the todo: try again
      </button>
    );
  }
  return (
    <h1 style={{ opacity: state.isFetching ? 0.5 : 1 }}>{state.data.title}</h1>
  );
}
```

The object's type is `UseQueryStateResult`, a union of three shapes told
apart by `status`. The object keeps its identity while nothing in it
changes.

## The fields

`useQueryState` returns these fields:

- `status`: `"pending"`, `"success"` or `"failure"`, with `isPending`,
  `isSuccess` and `isFailure` to match. A query is pending before its
  first fetch settles, after a [`clear`](https://effetch-query.monarcode.dev/docs/cache), and when it's
  `null`.
- `data`: the value, or its selection with `select`. A failed refetch keeps
  the last value as `data`.
- `error`: the typed error. It's `undefined` when the query died with a
  defect or was interrupted.
- `cause`: the failure's full `Cause`, which holds the error, the defect or
  the interruption.
- `isFetching`: true while a fetch runs, the first one or a refetch.
- `isPlaceholder`: true while `data` isn't the query's own value yet: see
  [Tell a placeholder from the real value](https://effetch-query.monarcode.dev/docs/react/as-object#tell-a-placeholder-from-the-real-value).
- `refetch`: refetches the query, and resolves when the refetch settles. It
  never rejects, and keeps its identity while the query stays the same.
- `result`: the `AsyncResult` the fields come from.

`error` is a union of every error the query can fail with. To handle each
by its `_tag`, match on `state.result`, or on `useQuery`'s result: see
[Read a query](https://effetch-query.monarcode.dev/docs/react).

**Details: when isFetching and refetch don't follow a fetch**

- In a server render, a query the cache doesn't have reads as fetching,
  though nothing fetches it there.
- A `paused` reader fetches nothing, so `isFetching` stays false for it.
- `refetch` resolves at once for a `null` query, and for a query that
  only paused readers use: see [Pause screens you can't see](https://effetch-query.monarcode.dev/docs/react/pause).

## Differences from TanStack Query

The fields are close to TanStack Query's, not the same. Coming from it,
these are the differences:

- `status` is `"failure"`, not `"error"`, and its flag is `isFailure`, not
  `isError`.
- `isPlaceholder` replaces `isPlaceholderData`.
- `refetch` resolves with nothing, not with the new result, and never
  rejects: a failure shows in the fields.
- `error` is `undefined` for a defect or an interruption. Read `cause` for
  those.
- There's no `isLoading`, `isRefetching` or `isStale`. For a refetch you
  started yourself, such as pull to refresh, use `useRefetch`'s
  `isRefetching`: see [Refetch on demand](https://effetch-query.monarcode.dev/docs/react/refetch).

## Tell a placeholder from the real value

Some values a component shows aren't the query's own yet: a
[placeholder](https://effetch-query.monarcode.dev/docs/queries/placeholders), such as the list's copy of a
todo, or the previous todo that `keepPrevious` keeps while the next one
loads. `isPlaceholder` is true for both. Use it to dim the data, or to turn
off what needs the real value, such as editing it:

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

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

export function TodoTitleInput({ id }: { readonly id: number }) {
  const state = useQueryState(todo({ params: { id } }), {
    keepPrevious: true,
  });

  if (state.status !== "success") {
    return null;
  }
  // Editing waits for this todo, not the one kept from before.
  return (
    <input defaultValue={state.data.title} disabled={state.isPlaceholder} />
  );
}
```

`isPlaceholder` stays true until the query's own value or failure replaces
the placeholder, and `isFetching` is true meanwhile. A failure's `data` is
always the query's own last value, so `isPlaceholder` is false there.

A `paused` reader fetches nothing, so it keeps showing a placeholder, with
`isPlaceholder` true and `isFetching` false, until it resumes.

Suspense treats a placeholder as a value. In the browser,
`useSuspenseQuery` doesn't suspend on one: it returns it as a waiting
`Success`. A server render doesn't show a placeholder, so there, and while
the page hydrates, `useSuspenseQuery` suspends until the query's own value
arrives.

## Read with Suspense

`useSuspenseQueryState` reads a query as
[`useSuspenseQuery`](https://effetch-query.monarcode.dev/docs/react/suspense) does, and returns the same
fields. It suspends until the query has a value, so `data` is always
there:

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

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

export function TodoHeading({ id }: { readonly id: number }) {
  const state = useSuspenseQueryState(todo({ params: { id } }));

  return (
    <h1>
      {state.data.title}
      {state.isFailure ? (
        <button onClick={() => void state.refetch()}>Couldn't refresh</button>
      ) : null}
    </h1>
  );
}
```

`status` is `"success"` or `"failure"`, never `"pending"`. A failure with
no value before it goes to the error boundary, as with `useSuspenseQuery`.
A refetch that fails after a success doesn't: `useSuspenseQuery` keeps
showing the success, and `useSuspenseQueryState` shows the failure, with
the earlier value as `data` and the typed `error` beside it. Its only
option is `select`.

## Read pages

`useInfiniteQueryState` and `useSuspenseInfiniteQueryState` read an
[infinite query](https://effetch-query.monarcode.dev/docs/queries/infinite) as `useInfiniteQuery` and
`useSuspenseInfiniteQuery` do. They return the fields, with `data.pages`
for the pages, beside the page controls:

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

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

export function ActivityList() {
  const state = useInfiniteQueryState(activity({ query: { team: "web" } }));

  if (state.status === "pending") {
    return <p>Loading…</p>;
  }
  return (
    <>
      <ul>
        {state.data?.pages
          .flatMap((page) => page.events)
          .map((event) => (
            <li key={event.id}>{event.text}</li>
          ))}
      </ul>
      {state.hasNextPage ? (
        <button
          disabled={state.isFetchingNextPage}
          onClick={() => void state.fetchNextPage()}
        >
          Load more
        </button>
      ) : null}
    </>
  );
}
```

A page that fails makes `status` `"failure"`, with the pages loaded before
it still in `data`. A failure on the first page has no pages, so `data` is
`undefined` there. `useSuspenseInfiniteQueryState` throws that one to the
error boundary instead, so its `data` is always there.

## Read several queries

`useQueriesState` reads a list of queries as
[`useQueries`](https://effetch-query.monarcode.dev/docs/react#read-several-queries) does, and returns an
object for each, in the same order:

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

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

export function SelectedTodos({
  ids,
}: {
  readonly ids: ReadonlyArray<number>;
}) {
  const states = useQueriesState(ids.map((id) => todo({ params: { id } })));

  return (
    <ul>
      {states.map((state, index) => (
        <li key={ids[index]}>
          {state.status === "success" ? state.data.title : "Loading…"}
        </li>
      ))}
    </ul>
  );
}
```

Each object keeps its identity while its query's result does, and its
`refetch` while the query stays in the list. A `null` entry is pending,
and its `refetch` resolves at once. It takes `paused`, as `useQueries`
does.

## What's next

- [Show a placeholder](https://effetch-query.monarcode.dev/docs/queries/placeholders): give a query a value to
  show while it loads.
- [Read a query](https://effetch-query.monarcode.dev/docs/react): match on the `AsyncResult` itself, select
  part of a value, or read several queries.
- [Refetch on demand](https://effetch-query.monarcode.dev/docs/react/refetch): refetch from a button, with a
  flag for that refetch only.
- [Coming from TanStack Query](https://effetch-query.monarcode.dev/docs/coming-from-tanstack-query): the rest
  of TanStack Query's names, mapped to Effetch Query's.