TanstackのuseQueryのdefault値を改めて確認しておく
retry: 3
を忘れていて予期せぬ挙動をさせてしまったので
これか
いやてか、改めて設定値多いな
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,
})
enabled: boolean
Set this to false to disable this query from automatically running.
ここでqueryKeyの変更による自動アプデを止められるんだ
retry: boolean | number | (failureCount: number, error: TError) => boolean
defaults to 3 on the client and 0 on the server
これこれ、これでぼくは失敗しました
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"が何を示しているんだろう。
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.
こんなこともできたんか、器用すぎ
staleTime: number | Infinity
Optional
Defaults to 0
これが実質キャッシュ時間?
こっちでコントロールか?
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
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: 0
でrefetchOnMount: true
だから、再レンダリングのたびに通信してる?mountって再レンダリングも入る?
あ、同じクエリを複数箇所で使った場合にrefetchするかどうか、みたいなのが重要なのかな。そう考えるとmountに再レンダリングは入らない気がしてきた?
別の場所で"re-render"っていう言葉使ってたから、mountはre-renderとは別だわ。
ここにめっちゃ詳しく書いてあった
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.
キャッシュデータがメモリに残る時間
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.
高機能すぎでしょきみ、すごいね
これも
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.
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.
おーこんなこともできたんか?
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
の違いはなんだろうか
initialData(キャッシュの初期データ)があればpending
になることはないからplaceholderDataは現れない?
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!
initialDataがあればqueryをスキップできるのはあってそう。staleTimeを設定すればの話だけど。
const result = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('/todos'),
initialData: initialTodos,
staleTime: 1000,
})
あー、こういうふうに使うのか
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)
},
})
placeholderDataはあくまでも仮初のデータとして振る舞うんやな
Placeholder data allows a query to behave as if it already has data, similar to the initialData option, but the data is not persisted to the cache. This comes in handy for situations where you have enough partial (or fake) data to render the query successfully while the actual data is fetched in the background.
似たような使い方だけど、こっちは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)
},
})
}
軽い気持ちで始めたら考えることたくさんあって降参