Closed24

TanstackのuseQueryのdefault値を改めて確認しておく

hajimismhajimism

retry: 3を忘れていて予期せぬ挙動をさせてしまったので

hajimismhajimism
hajimismhajimism

いやてか、改めて設定値多いな

const {
  data,
  dataUpdatedAt,
  error,
  errorUpdatedAt,
  failureCount,
  failureReason,
  fetchStatus,
  isError,
  isFetched,
  isFetchedAfterMount,
  isFetching,
  isInitialLoading,
  isLoading,
  isLoadingError,
  isPaused,
  isPending,
  isPlaceholderData,
  isRefetchError,
  isRefetching,
  isStale,
  isSuccess,
  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,
  throwOnError,
})
hajimismhajimism

enabled: boolean
Set this to false to disable this query from automatically running.

ここでqueryKeyの変更による自動アプデを止められるんだ

hajimismhajimism

retry: boolean | number | (failureCount: number, error: TError) => boolean
defaults to 3 on the client and 0 on the server

これこれ、これでぼくは失敗しました

hajimismhajimism

retryOnMount: boolean
If set to false, the query will not be retried on mount if it contains an error. Defaults to true.

これも知らんかったな。defaultだとエラーがあったら再レンダリング時にretryする?"mount"が何を示しているんだろう。

hajimismhajimism

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.

こんなこともできたんか、器用すぎ

hajimismhajimism

staleTime: number | Infinity
Optional
Defaults to 0

これが実質キャッシュ時間?

hajimismhajimism

こっちでコントロールか?

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

hajimismhajimism

refetchOnMount: boolean | "always" | ((query: Query) => 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.
If set to a function, the function will be executed with the query to compute the value

defaultだとstaleTime: 0refetchOnMount: trueだから、再レンダリングのたびに通信してる?mountって再レンダリングも入る?

hajimismhajimism

あ、同じクエリを複数箇所で使った場合にrefetchするかどうか、みたいなのが重要なのかな。そう考えるとmountに再レンダリングは入らない気がしてきた?

hajimismhajimism

別の場所で"re-render"っていう言葉使ってたから、mountはre-renderとは別だわ。

hajimismhajimism

gcTime: number | Infinity
Defaults to 5 * 60 * 1000 (5 minutes) or Infinity 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.

キャッシュデータがメモリに残る時間

hajimismhajimism

refetchOnWindowFocus: boolean | "always" | ((query: Query) => boolean | "always")
Optional
Defaults to true
If set to true, the query will refetch on window focus if the data is stale.

高機能すぎでしょきみ、すごいね

hajimismhajimism

これも

refetchOnReconnect: boolean | "always" | ((query: Query) => boolean | "always")
Optional
Defaults to true
If set to true, the query will refetch on reconnect if the data is stale.

hajimismhajimism

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 returned data value, but does not affect what gets stored in the query cache.

おーこんなこともできたんか?

hajimismhajimism

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

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 the pending state.
placeholderData is not persisted to the cache

の違いはなんだろうか

hajimismhajimism

initialData(キャッシュの初期データ)があればpendingになることはないからplaceholderDataは現れない?

hajimismhajimism

There may be times when you already have the initial data for a query available in your app and can simply provide it directly to your query. If and when this is the case, you can use the config.initialData option to set the initial data for a query and skip the initial loading state!

https://tanstack.com/query/latest/docs/react/guides/initial-query-data

initialDataがあればqueryをスキップできるのはあってそう。staleTimeを設定すればの話だけど。

const result = useQuery({
  queryKey: ['todos'],
  queryFn: () => fetch('/todos'),
  initialData: initialTodos,
  staleTime: 1000,
})
hajimismhajimism

あー、こういうふうに使うのか

const result = useQuery({
  queryKey: ['todo', todoId],
  queryFn: () => fetch('/todos'),
  initialData: () => {
    // Use a todo from the 'todos' query as the initial data for this todo query
    return queryClient.getQueryData(['todos'])?.find((d) => d.id === todoId)
  },
})
hajimismhajimism

似たような使い方だけど、こっちはcacheに入らないから不完全なデータでもOKと

function Todo({ blogPostId }) {
  const queryClient = useQueryClient();
  const result = useQuery({
    queryKey: ['blogPost', blogPostId],
    queryFn: () => fetch(`/blogPosts/${blogPostId}`),
    placeholderData: () => {
      // Use the smaller/preview version of the blogPost from the 'blogPosts'
      // query as the placeholder data for this blogPost query
      return queryClient
        .getQueryData(['blogPosts'])
        ?.find((d) => d.id === blogPostId)
    },
  })
}
hajimismhajimism

軽い気持ちで始めたら考えることたくさんあって降参

このスクラップは5ヶ月前にクローズされました