DocsBlog
  • 1.3.0

  • light

    dark

    system

    Switch mode
  • Cerberus

    Acheron

    Elysium

Get Started
Components
Data Grid
Signals
Styling
Theming

Get Started

OverviewReactivityData FetchingStores

Primitives

createSignalcreateQueryNewcreateMutationNewcreateComputedcreateEffectcreateStoreContextbatchonCleanupNewuntrackNew

Hooks

useQueryNewuseMutationuseReaduseSignaluseStoreNew

Components

ReactiveText

On this page

Loading...

Loading...

Loading...

Loading...

Using Queries

Learn how to used defined queries in React.

  • source
import { useQuery } from '@cerberus/signals'

Usage

useQuery allows you use a query factory (via createQuery) within the scope of a React component.

The return of useQuery is a read-only value which is the result of the query fetcher.

Query's have built in support for Suspense and Error Boundaries with no extra effort.

Using Queries

To use query factories within React components, simply pass in the defined query to the hook and bind the value in your JSX.

Initial Data

If you would like to bypass the initial fetch with pre-loaded data that matches the return of the query factory being used (e.g., parent server component fetch) - add and options Object as the last argument with the property initialData.

With Suspense

To utilize the native React Suspense API with your query, wrap the parent of the component using the query in Suspense as per requirements of the React API.

To learn more about Suspense, read the React docs.

With Error Boundaries

If a query errors out, createQuery will throw an error that will natively trigger an Error Boundary if you have one established.

To learn more about Error Boundaries, see the Error Boundary library on NPM.

API

useQuery accepts the following options:

ParamsRequiredDescription
Accessor<QueryState<T>>YesThe query to utilize.
QueryOptions<T>NoAdditional options to use for the query factory.

Return

useQuery returns the value of the Promise defined in createQuery.

Query Options

The QueryOption Object contains the following properties:

ParamsRequiredDescription
initialDataNoWhen provided will bypass the initial query fetch and instead return the value of initialData.
Copy
'use client'

import { Box, Stack } from '@/styled-system/jsx'
import { Button } from '@cerberus/react'
import { createQuery, useQuery, useSignal } from '@cerberus/signals'
import { Suspense } from 'react'

// Define Query Factory
const query = createQuery(fetchUser, 'get-user')

interface UserInfoProps {
  user: User['id']
}

function UserInfo(props: UserInfoProps) {
  const data = useQuery(query(props.user))
  return <pre>{JSON.stringify(data, null, 2)}</pre>
}

export function BasicDemo() {
  // pretend this is from route params instead of a signal. useSignal will force
  // the render update like a URL param change would.
  const [user, setUser] = useSignal<User['id']>(crypto.randomUUID())

  return (
    <Stack direction="column" justify="space-between" w="3/4">
      <Suspense fallback={<Box aria-busy h="96px" rounded="sm" w="full" />}>
        <UserInfo user={user} />
      </Suspense>

      <Button onClick={() => setUser(crypto.randomUUID())}>Change User</Button>
    </Stack>
  )
}

// API

type User = {
  id: string
  name: string
}

function fetchUser(id: User['id']): Promise<User> {
  return new Promise<User>((resolve) => {
    setTimeout(() => {
      resolve({ id, name: `User ${id}` })
    }, 500)
  })
}
'use client'

import { useQuery } from '@cerberus/signals'
import { queryUser } from './queries'
import { type User } from './db'

interface Props {
  id: string
  initialData: User
}

export function UserProfile(props: Props) {
  // 1. Cerberus sees `initialData`, instantly seeds the $O(1) Map,
  // and mounts the component with zero loading spinners or network waterfalls.
  const user = useQuery(queryUser(props.id), { initialData: props.initialData })

  if (!user) return null

  return <h1>{user.name}</h1>
}

On this page

  • Usage
  • Using Queries
  • Initial Data
  • With Suspense
  • With Error Boundaries
  • API
  • Return
  • Query Options
  • Edit this page on Github
{
  "id": "9dbeb4cd-e092-4552-9ed3-39449ec975bf",
  "name": "User 9dbeb4cd-e092-4552-9ed3-39449ec975bf"
}