Blitz is pivoting to framework agnostic toolkit. Click to learn more.
🚀Announcing Flightcontrol - Easily Deploy Blitz.js and Next.js to AWS 🚀
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,
  {
    dataUpdatedAt,
    error,
    errorUpdatedAt,
    failureCount,
    isError,
    isFetched,
    isFetchedAfterMount,
    isFetching,
    isIdle,
    isLoading,
    isLoadingError,
    isPlaceholderData,
    isPreviousData,
    isRefetchError,
    isStale,
    isSuccess,
    refetch,
    remove,
    status,
    setQueryData,
  }
] = useQuery(queryResolver, queryInputArguments, {
  cacheTime,
  enabled,
  initialData,
  initialDataUpdatedAt
  isDataEqual,
  keepPreviousData,
  notifyOnChangeProps,
  notifyOnChangePropsExclusions,
  onError,
  onSettled,
  onSuccess,
  queryKeyHashFn,
  refetchInterval,
  refetchIntervalInBackground,
  refetchOnMount,
  refetchOnReconnect,
  refetchOnWindowFocus,
  retry,
  retryOnMount,
  retryDelay,
  select,
  staleTime,
  structuralSharing,
  suspense,
  useErrorBoundary,
})

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 this query from automatically running.
    • Can be used for Dependent Queries.
  • retry: boolean | number | (failureCount: number, error: TError) => boolean
    • If false, failed queries will not retry by default.
    • If true, failed queries will retry infinitely.
    • If set to a number, e.g. 3, failed queries will retry until the failed query count meets that number.
  • retryOnMount: boolean
    • If set to false, the query will not be retried on mount if it contains an error. Defaults to true.
  • retryDelay: number | (retryAttempt: number, error: TError) => number
    • This function receives a retryAttempt integer and the actual Error 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: number | Infinity
    • The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on.
    • If set to Infinity, the data will never be considered stale
  • cacheTime: number | 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. When different cache times are specified, the longest one will be used.
    • If set to Infinity, will disable garbage collection
  • refetchInterval: false | number
    • 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
  • refetchOnMount: boolean | "always"
    • Optional
    • Defaults to true
    • If set to true, the query will refetch on mount if the data is stale.
    • If set to false, the query will not refetch on mount.
    • If set to "always", the query will always refetch on mount.
  • refetchOnWindowFocus: boolean | "always"
    • Optional
    • Defaults to true
    • If set to true, the query will refetch on window focus if the data is stale.
    • If set to false, the query will not refetch on window focus.
    • If set to "always", the query will always refetch on window focus.
  • refetchOnReconnect: boolean | "always"
    • Optional
    • Defaults to true
    • If set to true, the query will refetch on reconnect if the data is stale.
    • If set to false, the query will not refetch on reconnect.
    • If set to "always", the query will always refetch on reconnect.
  • notifyOnChangeProps: string[] | "tracked"
    • Optional
    • If set, the component will only re-render if any of the listed properties change.
    • If set to ['data', 'error'] for example, the component will only re-render when the data or error properties change.
    • If set to "tracked", access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
  • notifyOnChangePropsExclusions: string[]
    • Optional
    • If set, the component will not re-render if any of the listed properties change.
    • If set to ['isStale'] for example, the component will not re-render when the isStale property changes.
  • onSuccess: (data: TData) => void
    • Optional
    • This function will fire any time the query successfully fetches new data.
  • onError: (error: TError) => void
    • Optional
    • This function will fire if the query encounters an error and will be passed the error.
  • onSettled: (data?: TData, error?: TError) => void
    • Optional
    • This function will fire any time the query is either successfully fetched or errors and be passed either the data or error
  • select: (data: TData) => unknown
    • Optional
    • This option can be used to transform or select a part of the data returned by the query function.
  • suspense: boolean
    • Optional
    • Set this to false to disable suspense mode.
    • When true, useQuery will suspend when status === 'loading'
    • When true, useQuery will throw runtime errors when status === 'error'
  • initialData: TData | () => TData
    • 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
    • Initial data is considered stale by default unless a staleTime has been set.
    • initialData is persisted to the cache
  • initialDataUpdatedAt: number | (() => number | undefined)
    • Optional
    • If set, this value will be used as the time (in milliseconds) of when the initialData itself was last updated.
  • placeholderData: TData | () => TData
    • Optional
    • If set, this value will be used as the placeholder data for this particular query observer while the query is still in the loading data and no initialData has been provided.
    • placeholderData is not persisted to the cache
  • keepPreviousData: boolean
    • Optional
    • Defaults to false
    • If set, any previous data will be kept when fetching new data because the query key changed.
  • structuralSharing: boolean
    • Optional
    • Defaults to true
  • useErrorBoundary: boolean
    • Optional
    • Defaults to the global query config's useErrorBoundary value, which is false
    • Set this to true if you want query errors to be thrown in the render phase and propagate to the nearest error boundary.

Returns

[queryResult, queryExtras]

queryResult: TData
  • Defaults to undefined.
  • The last successfully resolved data for the query.
queryExtras: Object
  • status: String
    • Will be:
      • idle if the query is idle. This only happens if a query is initialized with enabled: false and no initial data is available.
      • loading if the query is in a "hard" loading state. This means there is no cached data and the query is currently fetching, eg isFetching === true
      • error if the query attempt resulted in an error. The corresponding error property has the error received from the attempted fetch
      • success if the query has received a response with no errors and is ready to display its data. The corresponding data property on the query is the data received from the successful fetch or if the query's enabled property is set to false and has not been fetched yet data is the first initialData supplied to the query on initialization.
  • isIdle: boolean
    • A derived boolean from the status variable above, provided for convenience.
  • isLoading: boolean
    • A derived boolean from the status variable above, provided for convenience.
  • isSuccess: boolean
    • A derived boolean from the status variable above, provided for convenience.
  • isError: boolean
    • A derived boolean from the status variable above, provided for convenience.
  • isLoadingError: boolean
    • Will be true if the query failed while fetching for the first time.
  • isRefetchError: boolean
    • Will be true if the query failed while refetching.
  • data: TData
    • Defaults to undefined.
    • The last successfully resolved data for the query.
  • dataUpdatedAt: number
    • The timestamp for when the query most recently returned the status as "success".
  • error: null | TError
    • Defaults to null
    • The error object for the query, if an error was thrown.
  • errorUpdatedAt: number
    • The timestamp for when the query most recently returned the status as "error".
  • isStale: boolean
    • Will be true if the data in the cache is invalidated or if the data is older than the given staleTime.
  • isPlaceholderData: boolean
    • Will be true if the data shown is the placeholder data.
  • isPreviousData: boolean
    • Will be true when keepPreviousData is set and data from the previous query is returned.
  • isFetched: boolean
    • Will be true if the query has been fetched.
  • isFetchedAfterMount: boolean
    • Will be true if the query has been fetched after the component mounted.
    • This property can be used to not show any previously cached data.
  • isFetching: boolean
    • Defaults to true so long as enabled is set to false
    • Will be true if the query is currently fetching, including background fetching.
  • failureCount: number
    • The failure count for the query.
    • Incremented every time the query fails.
    • Reset to 0 when the query succeeds.
  • refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>
    • A function to manually refetch the query.
    • If the query errors, the error will only be logged. If you want an error to be thrown, pass the throwOnError: true option
    • If cancelRefetch is true, then the current request will be cancelled before a new request is made
  • remove: () => void
    • A function to remove the query from the cache.
  • 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.