Blitz is now in beta! 🎉 1.0 expected this April
Back to Documentation Menu

useQuery

Topics

Jump to a Topic

Example

React Concurrent Mode is enabled by default for Blitz apps. So the <Suspense> component is used for loading states and <ErrorBoundary> is used to display errors. If you need, you can read the React Concurrent Mode Docs.

import {Suspense} from "react"
import {useQuery, useRouter, useParam} from "blitz"
import getProject from "app/projects/queries/getProject"
import ErrorBoundary from "app/components/ErrorBoundary"

function Project() {
  const router = useRouter()
  const projectId = useParam("projectId", "number")
  const [project] = useQuery(getProject, {where: {id: projectId}})

  return <div>{project.name}</div>
}

function WrappedProject() {
  return (
    <div>
      <ErrorBoundary
        fallback={(error) => <div>Error: {JSON.stringify(error)}</div>}
      >
        <Suspense fallback={<div>Loading...</div>}>
          <Project />
        </Suspense>
      </ErrorBoundary>
    </div>
  )
}

export default WrappedProject

For more examples and use cases, see the query usage documentation.

API

const [
  queryResult,
  {
    isFetching,
    failureCount,
    refetch,
    setQueryData,
  }
] = useQuery(queryResolver, queryInputArguments, {
  enabled,
  forceFetchOnMount,
  retry,
  retryDelay,
  staleTime,
  cacheTime,
  refetchInterval,
  refetchIntervalInBackground,
  refetchOnWindowFocus,
  refetchOnReconnect,
  notifiyOnStatusChange,
  onSuccess,
  onError,
  onSettled,
  suspense,
  initialData,
  refetchOnMount,
})

Arguments

  • queryResolver: A Blitz query resolver
    • Required
  • queryInputArguments
    • Required
    • The arguments that will be passed to queryResolver
  • options
    • Optional

Options

  • enabled: Boolean
    • Set this to false to disable automatic refetching when the query mounts or changes query keys.
    • To refetch the query, use the refetch method returned from the useQuery instance.
  • forceFetchOnMount: Boolean
    • Optional
    • Defaults to false
    • Set this to true to always fetch when the component mounts (regardless of staleness).
  • retry: Boolean | Int | Function(failureCount, error) => Boolean
    • If false, failed queries will not retry by default.
    • If true, failed queries will retry infinitely.
    • If set to an Int, e.g. 3, failed queries will retry until the failed query count meets that number.
    • If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false.
  • retryDelay: Function(retryAttempt: Int) => Int
    • This function receives a retryAttempt integer and returns the delay to apply before the next attempt in milliseconds.
    • A function like attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000) applies exponential backoff.
    • A function like attempt => attempt * 1000 applies linear backoff.
  • staleTime: Int | Infinity
    • The time in milliseconds that cache data remains fresh. After a successful cache update, that cache data will become stale after this duration.
    • If set to Infinity, query will never go stale
  • cacheTime: Int | Infinity
    • The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration.
    • If set to Infinity, will disable garbage collection
  • refetchInterval: false | Integer
    • Optional
    • If set to a number, all queries will continuously refetch at this frequency in milliseconds
  • refetchIntervalInBackground: Boolean
    • Optional
    • If set to true, queries that are set to continuously refetch with a refetchInterval will continue to refetch while their tab/window is in the background
  • refetchOnWindowFocus: Boolean
    • Optional
    • Set this to false to disable automatic refetching on window focus (useful, when refetchAllOnWindowFocus is set to true).
    • Set this to true to enable automatic refetching on window focus (useful, when refetchAllOnWindowFocus is set to false.
  • refetchOnReconnect: Boolean
    • Optional
    • Set this to true or false to enable/disable automatic refetching on reconnect for this query.
  • notifyOnStatusChange: Boolean
    • Optional
    • Whether a change to the query status should re-render a component.
    • If set to false, the component will only re-render when the actual data or error changes.
    • Defaults to true.
  • onSuccess: Function(data) => data
    • Optional
    • This function will fire any time the query successfully fetches new data.
  • onError: Function(err) => void
    • Optional
    • This function will fire if the query encounters an error and will be passed the error.
  • onSettled: Function(data, error) => data
    • Optional
    • This function will fire any time the query is either successfully fetched or errors and be passed either the data or error
  • initialData: any | Function() => any
    • Optional
    • If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet)
    • If set to a function, the function will be called once during the shared/root query initialization, and be expected to synchronously return the initialData
  • refetchOnMount: Boolean
    • Optional
    • Defaults to true
    • If set to false, will disable additional instances of a query to trigger background refetches
  • suspense: Boolean
    • Optional
    • Enabled by default. Set this to false to disable suspense mode.

Returns

[queryResult, queryExtras]

queryResult: Any
  • Defaults to undefined.
  • The last successfully resolved data for the query.
queryExtras: Object
  • isFetching: Boolean
    • Will be true if the query is currently fetching, including background fetching.
  • failureCount: Integer
    • The failure count for the query.
    • Incremented every time the query fails.
    • Reset to 0 when the query succeeds.
  • refetch() - Function({ force, throwOnError }) => void
    • A function to manually refetch the query if it is stale.
    • To bypass the stale check, you can pass the force: true option and refetch it regardless of it's freshness
    • If the query errors, the error will only be logged. If you want an error to be thrown, pass the throwOnError: true option
  • setQueryData() - Function(newData, opts) => Promise<void>
    • A function to manually update the cache for a query.
    • newData can be an object of new data or a function that receives the old data and returns the new data
    • This is often used to instantly update the cache after submitting a form
    • After updating the cache, this will automatically call refetch() to ensure the data is correct. Disable refetch by passing an options object {refetch: false} as the second argument.
    • See the Blitz mutation usage docs for example usage of setQueryData()

Idea for improving this page? Edit it on Github.