Skip to content

Cratis Arc query hooks in React

Cratis Arc’s generated query hooks let a React component fetch backend data and decide what to render while it waits or when a request fails. Call .use() on a generated proxy, then read the result’s state before rendering its data.

Arc generates query proxies from backend queries (controller-based and model-bound). These proxies expose static React helpers such as .use() and .useWithPaging().

See Backend Proxy Generation for setup details.

Inside a React component rendered beneath <Arc>, call the generated static use() method:

export const MyComponent = () => {
const [accounts, queryAccounts] = AllAccounts.use();
return (
<>
</>
);
};

The hook starts the request automatically. Here, accounts is a QueryResultWithState, not the account array: read accounts.data after checking readiness and success. Its data type comes from the backend query’s metadata.

Call queryAccounts() when you need to fetch again, such as after a user selects Refresh. The delegate updates the hook’s result state and returns Promise<void>; it does not return the account array.

The generated hook returns a tuple: an ordered array containing the result and any controls. Its shape depends on whether the query fetches once or observes updates, and whether it returns one model or a collection (an enumerable). You can omit trailing controls when destructuring, as the example does.

Proxy shape .use() / .useSuspense() .useWithPaging() / .useSuspenseWithPaging()
Ordinary single or enumerable [result, perform, setSorting] Enumerable only: [result, perform, setSorting, setPage, setPageSize]
Observable enumerable [result, setSorting] [result, setSorting, setPage, setPageSize]
Observable single [result] Not generated

An ordinary query’s second element is perform, the refresh delegate called queryAccounts above. An observable collection’s second element is setSorting, not a refresh function: the subscription delivers updates. See Observable Queries when you need live data.

Parameterized proxies emit an argument type named NameParameters, not INameParameters. Pass args first and, for collections, optional sorting next. For example, BooksForAuthor.use({ authorId }) passes a named argument object.

A parameterless collection takes sorting first, so AllBooks.use(sorting) needs no undefined placeholder. A parameterless single-result hook takes no arguments. The paging variants prepend pageSize to these positions; see Paging for page controls.

The query result type in React is QueryResultWithState. It implements the same IQueryResult contract as QueryResult and adds React-focused execution state.

Properties from the shared IQueryResult contract:

Property Description
data The actual data returned in the expected type.
isSuccess Whether the query completed successfully.
isReady Whether the result is ready to inspect. false means still waiting.
isAuthorized Whether the query was authorized.
isValid Whether the query input was valid.
validationResults Validation errors returned by the backend.
hasExceptions Whether exceptions were returned.
exceptionMessages Exception messages from the backend.
exceptionStackTrace Exception stack trace when available.
paging Paging metadata (page, size, totals) when paging is enabled.

React execution state:

Property Description
isPerforming Whether the query is currently fetching data.

Check isReady before deciding whether to show data or a failure. The initial React query state is not ready. isPerforming describes client work instead: the client can be fetching again while an earlier, ready result remains available. Disabled queries and locally created failure results are ready because no server result remains pending; readiness alone does not mean data was fetched successfully.

An observable query HTTP request can return 202 Accepted with isReady: false before the observable has produced its first result. In that waiting state, isSuccess is false and hasExceptions is false. Keep showing a waiting state rather than treating the response as a failure.

IQueryResult.isReady is optional for source compatibility: older Arc servers and third-party structural query-result objects may omit it. Arc normalizes query results received through its HTTP, WebSocket, and Server-Sent Events transports to isReady: true when the member is absent, while preserving an explicit false. SDK-produced QueryResult and QueryResultWithState instances always expose a concrete boolean.

With ordinary .use(), query failures are represented in the returned result, rather than thrown to an error boundary. Once isReady is true, check isAuthorized for access denial and isValid for input problems. Use validationResults to explain which inputs need attention. hasExceptions identifies exceptions; their details may be redacted by the server.

Render query data when the ready result is successful. Checking only !isSuccess cannot distinguish waiting from failure, and checking only data can mistake a query’s default empty value for a completed result. If a parent component should own the loading and error UI, see Suspense Queries for boundary-based handling and its retry limits.

Ordinary queries have no deadline by default. To bound a stalled read, call useQuery or useQueryWithPaging directly and pass an options object in the existing isEnabled position:

import { Paging } from '@cratis/arc/queries';
import { useQuery, useQueryWithPaging } from '@cratis/arc.react/queries';
// Inside a component, using the generated AllAccounts proxy:
const [accounts, refresh] = useQuery(AllAccounts, undefined, undefined, { timeoutMs: 5000 });
const [pagedAccounts] = useQueryWithPaging(AllAccounts, new Paging(0, 20), undefined, undefined, { timeoutMs: 5000 });

The options also accept isEnabled; existing boolean arguments continue to work. Generated .use() helpers do not expose hook deadline options. The returned refresh delegate accepts an optional second argument to override the hook deadline for one execution: await refresh(undefined, { timeoutMs: 1000 }).

On expiry, the hook stops performing and returns an unsuccessful, ready result with hasExceptions: true and a message such as Query timed out after 5000 ms.. The request’s abort controller is aborted when available. A late response cannot replace the timeout result, even if the transport ignores abort. A subsequent refresh can succeed normally.

A positive, finite timeoutMs enables the deadline; zero, negative or nonfinite values disable it. Deadlines cover one execution, including waiting for a superseding shared request. Timers are cleared on completion, supersession by this hook, or unmount. Unmounting does not abort a request another hook may still need.

Pass query inputs as a named object to the generated hook. The backend declares those inputs, and the proxy gives them TypeScript types. These examples declare an optional filter input for finding accounts by name:

[HttpGet("starting-with")]
public IEnumerable<DebitAccount> StartingWith([FromQuery] string? filter)
{
var filterDocument = Builders<DebitAccount>
.Filter
.Regex("name", $"^{filter ?? string.Empty}.*");
return _collection.Find(filterDocument).ToList();
}

View C# snippet source on GitHub

The C# controller action binds filter from the query string with [FromQuery]. The JVM examples take it as a query-method parameter on the read model: a companion-object method in Kotlin or a static method in Java. The TypeScript backend declares it with argument('filter', String, { optional: true }). Generated imports and paths depend on the backend’s configuration.

Use the parameterized proxy from React:

export const MyComponent = () => {
const [accounts, queryAccounts] = StartingWith.use({ filter: '' });
return (
<>
</>
);
};

An enabled hook fetches again whenever any argument changes — optional arguments such as filter as well as required ones. Arguments are compared by their serialized value, so passing a new object with the same values does not trigger a request. Each set of arguments also gets its own cached result; see query instance caching.

Ordinary query fetches use httpHeadersCallback. Native EventSource/WebSocket handshakes cannot attach those arbitrary headers; SSE control POSTs are separate fetch requests. Cookies are browser-managed, not configurable Cookie request headers. See the transport credentials matrix.