Movatterモバイル変換


[0]ホーム

URL:


TanStack
Queryv5v5
Auto
Log In
Documentation
Framework
Version
Guides & Concepts
Framework
Version
Guides & Concepts

useQuery

tsx
const {  data,  dataUpdatedAt,  error,  errorUpdatedAt,  failureCount,  failureReason,  fetchStatus,  isError,  isFetched,  isFetchedAfterMount,  isFetching,  isInitialLoading,  isLoading,  isLoadingError,  isPaused,  isPending,  isPlaceholderData,  isRefetchError,  isRefetching,  isStale,  isSuccess,  isEnabled,  promise,  refetch,  status,} = useQuery(  {    queryKey,    queryFn,    gcTime,    enabled,    networkMode,    initialData,    initialDataUpdatedAt,    meta,    notifyOnChangeProps,    placeholderData,    queryKeyHashFn,    refetchInterval,    refetchIntervalInBackground,    refetchOnMount,    refetchOnReconnect,    refetchOnWindowFocus,    retry,    retryOnMount,    retryDelay,    select,    staleTime,    structuralSharing,    subscribed,    throwOnError,  },  queryClient,)
const {  data,  dataUpdatedAt,  error,  errorUpdatedAt,  failureCount,  failureReason,  fetchStatus,  isError,  isFetched,  isFetchedAfterMount,  isFetching,  isInitialLoading,  isLoading,  isLoadingError,  isPaused,  isPending,  isPlaceholderData,  isRefetchError,  isRefetching,  isStale,  isSuccess,  isEnabled,  promise,  refetch,  status,} = useQuery(  {    queryKey,    queryFn,    gcTime,    enabled,    networkMode,    initialData,    initialDataUpdatedAt,    meta,    notifyOnChangeProps,    placeholderData,    queryKeyHashFn,    refetchInterval,    refetchIntervalInBackground,    refetchOnMount,    refetchOnReconnect,    refetchOnWindowFocus,    retry,    retryOnMount,    retryDelay,    select,    staleTime,    structuralSharing,    subscribed,    throwOnError,  },  queryClient,)

Parameter1 (Options)

  • queryKey: unknown[]
    • Required
    • The query key to use for this query.
    • The query key will be hashed into a stable hash. SeeQuery Keys for more information.
    • The query will automatically update when this key changes (as long asenabled is not set tofalse).
  • queryFn: (context: QueryFunctionContext) => Promise<TData>
    • Required, but only if no default query function has been defined SeeDefault Query Function for more information.
    • The function that the query will use to request data.
    • Receives aQueryFunctionContext
    • Must return a promise that will either resolve data or throw an error. The data cannot beundefined.
  • enabled: boolean | (query: Query) => boolean
    • Set this tofalse to disable this query from automatically running.
    • Can be used forDependent Queries.
  • networkMode: 'online' | 'always' | 'offlineFirst'
    • optional
    • defaults to'online'
    • seeNetwork Mode for more information.
  • retry: boolean | number | (failureCount: number, error: TError) => boolean
    • Iffalse, failed queries will not retry by default.
    • Iftrue, failed queries will retry infinitely.
    • If set to anumber, e.g.3, failed queries will retry until the failed query count meets that number.
    • defaults to3 on the client and0 on the server
  • retryOnMount: boolean
    • If set tofalse, the query will not be retried on mount if it contains an error. Defaults totrue.
  • retryDelay: number | (retryAttempt: number, error: TError) => number
    • This function receives aretryAttempt integer and the actual Error and returns the delay to apply before the next attempt in milliseconds.
    • A function likeattempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000) applies exponential backoff.
    • A function likeattempt => attempt * 1000 applies linear backoff.
  • staleTime: number | 'static' | ((query: Query) => number | 'static')
    • Optional
    • Defaults to0
    • The time in milliseconds after which data is considered stale. This value only applies to the hook it is defined on.
    • If set toInfinity, the data will not be considered stale unless manually invalidated
    • If set to a function, the function will be executed with the query to compute astaleTime.
    • If set to'static', the data will never be considered stale
  • gcTime: number | Infinity
    • Defaults to5 * 60 * 1000 (5 minutes) orInfinity during SSR
    • 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 garbage collection times are specified, the longest one will be used.
    • Note: the maximum allowed time is about24 days, although it is possible to work around this limit usingtimeoutManager.setTimeoutProvider.
    • If set toInfinity, will disable garbage collection
  • queryKeyHashFn: (queryKey: QueryKey) => string
    • Optional
    • If specified, this function is used to hash thequeryKey to a string.
  • refetchInterval: number | false | ((query: Query) => number | false | undefined)
    • Optional
    • If set to a number, all queries will continuously refetch at this frequency in milliseconds
    • If set to a function, the function will be executed with the query to compute a frequency
  • refetchIntervalInBackground: boolean
    • Optional
    • If set totrue, queries that are set to continuously refetch with arefetchInterval will continue to refetch while their tab/window is in the background
  • refetchOnMount: boolean | "always" | ((query: Query) => boolean | "always")
    • Optional
    • Defaults totrue
    • If set totrue, the query will refetch on mount if the data is stale.
    • If set tofalse, the query will not refetch on mount.
    • If set to"always", the query will always refetch on mount (except whenstaleTime: 'static' is used).
    • If set to a function, the function will be executed with the query to compute the value
  • refetchOnWindowFocus: boolean | "always" | ((query: Query) => boolean | "always")
    • Optional
    • Defaults totrue
    • If set totrue, the query will refetch on window focus if the data is stale.
    • If set tofalse, the query will not refetch on window focus.
    • If set to"always", the query will always refetch on window focus (except whenstaleTime: 'static' is used).
    • If set to a function, the function will be executed with the query to compute the value
  • refetchOnReconnect: boolean | "always" | ((query: Query) => boolean | "always")
    • Optional
    • Defaults totrue
    • If set totrue, the query will refetch on reconnect if the data is stale.
    • If set tofalse, the query will not refetch on reconnect.
    • If set to"always", the query will always refetch on reconnect (except whenstaleTime: 'static' is used).
    • If set to a function, the function will be executed with the query to compute the value
  • notifyOnChangeProps: string[] | "all" | (() => string[] | "all" | undefined)
    • 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 thedata orerror properties change.
    • If set to"all", the component will opt-out of smart tracking and re-render whenever a query is updated.
    • If set to a function, the function will be executed to compute the list of properties.
    • By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
  • select: (data: TData) => unknown
    • Optional
    • This option can be used to transform or select a part of the data returned by the query function. It affects the returneddata value, but does not affect what gets stored in the query cache.
    • Theselect function will only run ifdata changed, or if the reference to theselect function itself changes. To optimize, wrap the function inuseCallback.
  • 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 calledonce during the shared/root query initialization, and be expected to synchronously return the initialData
    • Initial data is considered stale by default unless astaleTime has been set.
    • initialDatais persisted to the cache
  • initialDataUpdatedAt: number | (() => number | undefined)
    • Optional
    • If set, this value will be used as the time (in milliseconds) of when theinitialData itself was last updated.
  • placeholderData: TData | (previousValue: TData | undefined, previousQuery: Query | undefined) => TData
    • Optional
    • If set, this value will be used as the placeholder data for this particular query observer while the query is still in thepending state.
    • placeholderData isnot persisted to the cache
    • If you provide a function forplaceholderData, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance.
  • structuralSharing: boolean | (oldData: unknown | undefined, newData: unknown) => unknown
    • Optional
    • Defaults totrue
    • If set tofalse, structural sharing between query results will be disabled.
    • If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values.
  • subscribed: boolean
    • Optional
    • Defaults totrue
    • If set tofalse, this instance ofuseQuery will not be subscribed to the cache. This means it won't trigger thequeryFn on its own, and it won't receive updates if data gets into cache by other means.
  • throwOnError: undefined | boolean | (error: TError, query: Query) => boolean
    • Set this totrue if you want errors to be thrown in the render phase and propagate to the nearest error boundary
    • Set this tofalse to disablesuspense's default behavior of throwing errors to the error boundary.
    • If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (true) or return the error as state (false)
  • meta: Record<string, unknown>
    • Optional
    • If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever thequery is available, and is also part of theQueryFunctionContext provided to thequeryFn.

Parameter2 (QueryClient)

  • queryClient?: QueryClient
    • Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.

Returns

  • status: QueryStatus
    • Will be:
      • pending if there's no cached data and no query attempt was finished yet.
      • error if the query attempt resulted in an error. The correspondingerror 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 correspondingdata property on the query is the data received from the successful fetch or if the query'senabled property is set tofalse and has not been fetched yetdata is the firstinitialData supplied to the query on initialization.
  • isPending: boolean
    • A derived boolean from thestatus variable above, provided for convenience.
  • isSuccess: boolean
    • A derived boolean from thestatus variable above, provided for convenience.
  • isError: boolean
    • A derived boolean from thestatus variable above, provided for convenience.
  • isLoadingError: boolean
    • Will betrue if the query failed while fetching for the first time.
  • isRefetchError: boolean
    • Will betrue if the query failed while refetching.
  • data: TData
    • Defaults toundefined.
    • The last successfully resolved data for the query.
  • dataUpdatedAt: number
    • The timestamp for when the query most recently returned thestatus as"success".
  • error: null | TError
    • Defaults tonull
    • The error object for the query, if an error was thrown.
  • errorUpdatedAt: number
    • The timestamp for when the query most recently returned thestatus as"error".
  • isStale: boolean
    • Will betrue if the data in the cache is invalidated or if the data is older than the givenstaleTime.
  • isPlaceholderData: boolean
    • Will betrue if the data shown is the placeholder data.
  • isFetched: boolean
    • Will betrue if the query has been fetched.
  • isFetchedAfterMount: boolean
    • Will betrue if the query has been fetched after the component mounted.
    • This property can be used to not show any previously cached data.
  • fetchStatus: FetchStatus
    • fetching: Istrue whenever the queryFn is executing, which includes initialpending as well as background refetches.
    • paused: The query wanted to fetch, but has beenpaused.
    • idle: The query is not fetching.
    • seeNetwork Mode for more information.
  • isFetching: boolean
    • A derived boolean from thefetchStatus variable above, provided for convenience.
  • isPaused: boolean
    • A derived boolean from thefetchStatus variable above, provided for convenience.
  • isRefetching: boolean
    • Istrue whenever a background refetch is in-flight, whichdoes not include initialpending
    • Is the same asisFetching && !isPending
  • isLoading: boolean
    • Istrue whenever the first fetch for a query is in-flight
    • Is the same asisFetching && isPending
  • isInitialLoading: boolean
    • deprecated
    • An alias forisLoading, will be removed in the next major version.
  • isEnabled: boolean
    • Istrue if this query observer is enabled,false otherwise.
  • failureCount: number
    • The failure count for the query.
    • Incremented every time the query fails.
    • Reset to0 when the query succeeds.
  • failureReason: null | TError
    • The failure reason for the query retry.
    • Reset tonull when the query succeeds.
  • errorUpdateCount: number
    • The sum of all errors.
  • 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 thethrowOnError: true option
    • cancelRefetch?: boolean
      • Defaults totrue
        • Per default, a currently running request will be cancelled before a new request is made
      • When set tofalse, no refetch will be made if there is already a request running.
  • promise: Promise<TData>
    • A stable promise that will be resolved with the data of the query.
    • Requires theexperimental_prefetchInRender feature flag to be enabled on theQueryClient.

    [8]ページ先頭

    ©2009-2025 Movatter.jp