API reference › @evolu/vue › useQuery

function useQuery<
  S extends Readonly<
    Record<string, Readonly<Record<string, AnyStandardSchemaV1>>>
  >,
  R extends Row,
>(
  query: Query<S, R>,
  __namedParameters?: UseQueryOptions,
): Readonly<Ref<QueryRows<R>>>;

Defined in: useQuery.ts:84

Load and subscribe to the query, returning a ref that stays in sync with Evolu changes.

The rows are empty until the query loads, so to tell a loading query from an empty one, an async setup under <Suspense> awaits waitForRows. When SQLite fails the query, the rows stay empty or show rows the query loaded earlier in this Evolu instance, so they do not signal the failure; waitForRows rejects with it. A failed load that no waitForRows awaits, also a cached failure, is reported as an unhandled rejection. When SQLite fails a later refresh, the rows keep their values, and nothing is reported.

To start loading earlier, such as in a router guard, call evolu.loadQuery. The composable then reuses that load unless a mutation or sync drops it first.

During server rendering, it only loads the query, so the rows are empty, as on the client before the query loads. Server rendering starts when the server renderer does, so a call on the server before that, such as from a store that a router guard uses first, subscribes as on the client.

Example

import {
  assertType,
  createQueryBuilder,
  testEvoluSchema,
  type Evolu,
  type QueryRows,
  type TestEvoluSchema,
} from "@evolu/common";
import { useQuery } from "@evolu/vue";

const createQuery = createQueryBuilder(testEvoluSchema);
const allTodos = createQuery((db) => db.selectFrom("todo").selectAll());

// Call composables in component setup.
const useTodos = () => useQuery(allTodos);

// Load the rows without subscribing to changes.
const useTodosOnce = () => useQuery(allTodos, { once: true });

// Prefetch the rows, for example in a router guard. useQuery then reuses
// that load unless a mutation or sync drops it first.
const prefetchTodos = (evolu: Evolu<TestEvoluSchema>) =>
  evolu.loadQuery(allTodos);

type TodoRows = QueryRows<typeof allTodos.Row>;
assertType<
  [
    ReturnType<typeof useTodos>["value"],
    ReturnType<typeof useTodosOnce>["value"],
    ReturnType<typeof prefetchTodos>,
  ],
  [TodoRows, TodoRows, Promise<TodoRows>]
>();