DocsBlog
  • 1.1.2

  • light

    dark

    system

    Switch mode
  • Cerberus

    Acheron

    Elysium

Get Started
Components
Data Grid
Signals
Styling
Theming

Get Started

OverviewReactivityData FetchingStores

Primitives

createSignalcreateQuerycreateMutationcreateComputedcreateEffectcreateStoreContextbatch

Hooks

useQueryuseMutationuseReaduseSignal

Components

ReactiveText

On this page

  • Edit this page on Github

Using Queries

Learn how to used defined queries in React.

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

Usage

useQuery allows you call a defined query (via createQuery) to obtain the signal-based value for display within your React component.

The return of useQuery is a read-only value which is the result of calling an Accessor.

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

Using Queries

To obtain a query value, simply pass in the defined query to the hook and bind the value in your JSX.

With Suspense

To utilize the native React Suspense API with your query, simply wrap the parent of the component calling 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>>trueThe query to utilize.

Return

useQuery returns the value of the Promise defined in createQuery.

Copy
'use client'

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

type User = {
  id: string
  name: string
}

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

const [currentUser, setCurrentUser] = createSignal<User['id']>(crypto.randomUUID())

// 1. Define the query
const query = createQuery(currentUser, fetchUser)

function UserInfo() {
  // 2. Trigger the query
  const data = useQuery(query)
  return <pre>{JSON.stringify(data, null, 2)}</pre>
}

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

      <Button onClick={() => setCurrentUser(crypto.randomUUID())}>Change User</Button>
    </Stack>
  )
}
{
  "id": "411809ca-e360-4f6f-aa8f-2b0e574dac8b",
  "name": "User 411809ca-e360-4f6f-aa8f-2b0e574dac8b"
}