SR
Click to open github profile
Hooks

useCraftQuery

Learn how to use the useCraftQuery hook.


This hook provides a simple way to fetch data from your Craft CMS Backend. It leverages the JS SDK to build query URLs and fetch for fetching data in Client Components.

Element Types

// query addresses
const { data, error, loading } = useCraftQuery('addresses').one()
// or use the shorthand
const { data, error, loading } = useCraftAddress().one()

// query assets
const { data, error, loading } = useCraftQuery('assets').one()
// or use the shorthand
const { data, error, loading } = useCraftAsset().one()

// query entry
const { data, error, loading } = useCraftQuery('entries').one()
// or use the shorthand
const { data, error, loading } = useCraftEntry().one()

// query users
const { data, error, loading } = useCraftQuery('users').one()
// or use the shorthand
const { data, error, loading } = useCraftUser().one()

Execute Query

By using the one() or the all() methode the fetch gets executed. If you just building your query and are not executing it with one() or all() you need not to it.

const query = useCraftQuery('entries').section('news')

// Fetch a single entry
const { data: singleEntry } = query.one()

// Fetch all entries
const { data: allEntries } = query.all()

Available Methods

useCraftQuery supports all methods from js-craftcms-api.

Note

For the full list of available methods, see the documentation here.

In addition, the following methods are available for executing the query:

MethodDescriptionType
oneFetch one elementvoid
allFetch all elementsvoid

Example

// fetch without type definition
const { data, error, loading } = useCraftQuery('entries')
  .section('news')
  .fields(['title'])
  .limit(3)
  .all()

// with ts
type CraftEntry = {
  title: string
}
const { data, error, loading } = useCraftQuery<CraftEntry, 'entries'>('entries')
  .section('news')
  .fields(['title'])
  .limit(3)
  .all()

// or using the shorthand
const { data, error, loading } = useCraftEntry<CraftEntry>()
  .section('news')
  .fields(['title'])
  .limit(3)
  .all()

Types

type ElementType = 'addresses' | 'assets' | 'entries' | 'users'

export function useCraftQuery<ResT, T extends ElementType>(elementType: T): QueryBuilder<T> & {
  one(): {
    data: ResT | null;
    loading: boolean;
    error: string | null;
  };
  all(): {
    data: ResT | null;
    loading: boolean;
    error: string | null;
  };
}

Copyright © 2025 Samuel Reichör