【React Query】useQuery quick start

​​​​logo

React Query is often described as the data fetching library that React lacks, but technically it makes fetching, caching, syncing, and updating server state a breeze in React applications.

useQuery is the most commonly used hook of react-query, not one of them.

1. How to use

const {
    
    
   data,
   dataUpdatedAt,
   error,
   errorUpdatedAt,
   failureCount,
   isError,
   isFetched,
   isFetchedAfterMount,
   isFetching,
   isIdle,
   isLoading,
   isLoadingError,
   isPlaceholderData,
   isPreviousData,
   isRefetchError,
   isRefetching,
   isStale,
   isSuccess,
   refetch,
   remove,
   status,
 } = useQuery(queryKey, queryFn?, {
    
    
   cacheTime,
   enabled,
   initialData,
   initialDataUpdatedAt
   isDataEqual,
   keepPreviousData,
   meta,
   notifyOnChangeProps,
   notifyOnChangePropsExclusions,
   onError,
   onSettled,
   onSuccess,
   placeholderData,
   queryKeyHashFn,
   refetchInterval,
   refetchIntervalInBackground,
   refetchOnMount,
   refetchOnReconnect,
   refetchOnWindowFocus,
   retry,
   retryOnMount,
   retryDelay,
   select,
   staleTime,
   structuralSharing,
   suspense,
   useErrorBoundary,
 })
 
 // or using the object syntax
 
 const result = useQuery({
    
    
   queryKey,
   queryFn,
   enabled,
 })

2. Options

  • queryKey: string | unknown[]

    • required fields
    • The query key to use for this query and unique to the data being queried
    • Key-values ​​can be as simple as strings or as complex as arrays of many strings and nested objects
    • When this key changes, the query will be automatically updated (as long as enabled is not set to false)

    queryKey as a unique key value will be used internally in React Query to retrieve data, cache and share queries throughout the program, so you can use a specific key to cache some specific interface data. And the change of queryKey will cause the query to be updated, so you can set the interface field to queryKey, such as: useQuery(['todos', { page, status }], …)

  • queryFn: (context: QueryFunctionContext) => Promise<TData>

    • Mandatory items, (can be left blank after defining the default query function)
    • Query function that will be used to request data.
    • Receives a QueryFunctionContext object with the following variables
    • Must return a promise that will parse the data or throw an error
  • enabled: boolean

    • When false, queryFn will not be executed automatically
    • Sometimes we can judge whether to execute the query based on specific parameters
 // 获取用户
 const {
    
     data: user } = useQuery(['user', email], getUserByEmail)
 
 const userId = user?.id
 
 // 获取该用户的项目
 const {
    
     isIdle, data: projects } = useQuery(
   ['projects', userId],
   getProjectsByUser,
   {
    
    
     // 在userId获取到之前,查询不会执行
     enabled: !!userId,
   }
 )
  • retry: boolean | number | (failureCount: number, error: TError) => boolean

    • true: the query will be repeated indefinitely after the query fails
    • false: by default no failed queries will be retried
    • number: failed queries will be retried until the failed query count meets this number
  • retryOnMount: boolean

    • The default is true, if set to false, if there is an error when the component loads, it will not be re-queried
  • retryDelay: number | (retryAttempt: number, error: TError) => number

    • Delay time for requery
  • staleTime: number | Infinity

    • optional, default is 0
    • Time in milliseconds after which data is considered stale
    • If set to Infinity, data will never be considered expired
  • cacheTime: number | Infinity

    • The default is 5 minutes
    • After the cached data of the query has not been used for more than this period of time, the cached data will be recycled
    • If set to Infinity, data reclamation will be disabled
  • queryKeyHashFn: (queryKey: QueryKey) => string

    • optional
    • If specified, the function used to process the queryKey as a string
  • refetchInterval: number | false | ((data: TData | undefined, query: Query) => number | false)

    • optional
    • If set to a number, all queries will be refreshed continuously at that frequency, in milliseconds
    • If set to a function, the function will be executed with the latest data and query to calculate the frequency
  • refetchIntervalInBackground: boolean

    • optional
    • If set to true, keep firing refetchInterval while the tab/window is in the background
  • refetchOnMount: boolean | “always” | ((query: Query) => boolean | “always”)

    • optional, default is true
    • If set to true, the query will be re-executed on component load if the data is out of date
    • If set to false, the query will not be re-executed on component load
    • If set to "always", the query will always be re-executed on component load
    • If set to a function, the function will be executed using a query to calculate the value
  • refetchOnWindowFocus: boolean | “always” | ((query: Query) => boolean | “always”)

    • optional, default is true
    • If set to true, the query will refetch if the data expires when the window gets focus
    • If set to false, the query will not be reacquired when the window gains focus
    • If set to "Always", the query will always be reacquired when the window gains focus
    • If set to a function, the function will be executed using a query to calculate the value
  • refetchOnReconnect: boolean | “always” | ((query: Query) => boolean | “always”)

    • optional, default is true
    • If set to true, the query will be re-executed on reconnect if the data is out of date
    • If set to false, the query will not be re-executed on reconnect
    • If set to 'always', the query will always reconnect on reconnect
    • If set to a function, the function will be executed using a query to calculate the value
  • notifyOnChangeProps: string[] | “tracked”

    • optional
    • If set, the component will only re-render if any of the listed properties change
    • For example, if set to ['data', 'error'], the component will only re-render if the data or error properties change.
    • If set to "tracked", access to the property will be tracked and the component will only re-render if one of the tracked properties changes.
  • notifyOnChangePropsExclusions: string[]

    • optional
    • If set, the component will not re-render if any of the listed properties change.
    • For example, if set to ['isTale'], the component will not re-render when the isStale property changes.
  • onSuccess: (data: TData) => void

    • optional
    • This function will be executed whenever the query successfully gets new data or the cache is updated via setQueryData
  • onError: (error: TError) => void

    • optional
    • If the query encounters an error and will be passed the error, this function will execute
  • onSettled:(data?: TData, error?: TError) => void

    • optional
    • This function will be fired when the query is fetched successfully or on error, and passed the data or error
  • select: (data: TData) => unknown

    • optional
    • This option can be used to transform or select part of the data returned by query functions
  • suspense: boolean

    • optional
    • Set this to true to enable suspense mode.
    • If true, useQuery will hang when status == "loading"
    • If true, useQuery will throw a runtime error when status=="error"
  • initialData: TData | () => TData

    • optional
    • If set, as initial data for the query cache (as long as the query has not been created or cached yet)
    • If set to a function, the function will be called once during share/root query initialization and expect initialData to be returned synchronously
      • By default, initial data is considered stale unless staleTime is set.
      • initialData is persisted to the cache
  • initialDataUpdatedAt: number | (() => number | undefined)

    • optional
    • If set, this value will be used as the time in milliseconds when initialData itself was last updated.
  • placeholderData: TData | () => TData

    • optional
    • If set, the value will be used as placeholder data for this particular query watcher when the query is still loading data and initialData is not provided.
    • Placeholder data is not persisted to cache
  • keepPreviousData: boolean

    • optional, default is false
    • If set, when fetching new data, all previous data will be preserved since the query key has changed
  • structuralSharing: boolean

    • optional, default is true
    • If set to false, structure sharing between query results will be disabled
  • useErrorBoundary: undefined | boolean | (error: TError, query: Query) => boolean

    • The default is the useErrorBoundary value of the global query configuration, which is undefined
      • Set this to true if you want errors thrown during the render phase to be propagated to the nearest error boundary
      • Setting this to false disables suspend's default behavior of throwing errors to error boundaries.
      • If set to a function, it will be passed the error and the query, and should return a boolean indicating whether to display the error in the error boundary (true) or return the error as a status (false)
  • meta: Record<string, unknown>

    • optional
    • If set, stores additional information about query cache entries, which can be used as needed. It will be accessible wherever the query is available, and is also part of the QueryFunctionContext provided to queryFn

3. Returns

  • status: String

    • idle: idle. This only happens when the query is initialized with enabled:false and no initial data is available
    • loading: Loading. This means that no data is cached and the query is currently fetching eg isFetching==true
    • error: The result of the query returns an error
    • success: The query is successful if it has received a response without errors and is ready to display its data. The corresponding data property on the query is the data received from a successful fetch, or if the query's enabled property is set to false and has not been fetched, the data is the first initialData provided to the query on initialization
  • isIdle : boolean

    • Boolean values ​​diffracted from the status variable above, provided for convenience
  • isLoading: boolean

    • Boolean values ​​diffracted from the status variable above, provided for convenience
  • isSuccess: boolean

    • Boolean values ​​diffracted from the status variable above, provided for convenience
  • isError: boolean

    • Boolean values ​​diffracted from the status variable above, provided for convenience
  • isLoadingError: boolean

    • true if the query failed on first execution
  • isRefetchError: boolean

    • true if the query failed when requeried
  • data: TData

    • default undefined
    • The data of the last successfully parsed query
  • dataUpdatedAt: number

    • The most recent timestamp for which the query returned a status of "success"
  • error: null | TError

    • default null
    • If an error is thrown, the error object for the query is returned.
  • errorUpdatedAt: number

    • Query the most recent timestamp with status "error"
  • isStale: boolean

    • true if the data in the cache is invalid or the data is older than the given staleTime
  • isPlaceholderData: boolean

    • true if the displayed data is placeholder data
  • isPreviousData: boolean

    • Will be true when keepPreviousData is set and returns data from the previous query
  • isFetched: boolean

    • true if the query has been executed
  • isFetchedAfterMount: boolean

    • true if the query was fetched after the component was loaded
    • This property can be used to not display any previously cached data
  • isFetching: boolean

    • True whenever the request is running, this includes initial loading and background references.
    • True if the query is currently fetching (including background fetching).
  • isRefetching: boolean

    • true when a background reload is in progress (excluding the initial load)
    • Same as (isFetching && !isLoading)
  • failureCount: number

    • Failed count for queries
    • Incremented each time a query fails
    • Reset to 0 on successful query
  • errorUpdateCount: number

    • sum of all errors
  • refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise

    • Function to manually re-execute the query
    • If the query is wrong, just log the error. If you want errors to be thrown, pass the throwOnError: true option
    • If cancelRefetch is true, the current request will be canceled before a new request is made
  • remove: () => void

    • Function to remove query from cache

Guess you like

Origin blog.csdn.net/qq_38629292/article/details/128179065