Suspense勉強会
code: hoge.tsx
const TextFromApi: FC = () => {
// const { data: text, isLoading } = useQuery({
// queryFn: () => {
// console.log('before some api call')
// return someApiCall()
// },
// });
if (cache === null) {
throw new Promise<void>(resolve => {
someApiCall().then(message => {
cache = message;
resolve();
})
});
}
// console.log("isLoading: ", isLoading);
// console.log("text: ", text);
return <>{cache}</>;
};
tanstack queryはcacheがないとPromiseをThrowする
code:render.tsx
// render:
// try {
// TextFromApi()
// } catch(promise) {
// render(fallback)
// promise.then(() => goto render )
//
suspenseはthrowをcatchして、resolveされるまではfallbackに指定されたコンポーネントを表示する
StaleTime と CacheTime
StaleTime: The duration until a query transitions from fresh to stale. As long as the query is fresh, data will always be read from the cache only - no network request will happen! If the query is stale (which per default is: instantly), you will still get data from the cache, but a background refetch can happen under certain conditions.
CacheTime: The duration until inactive queries will be removed from the cache. This defaults to 5 minutes. Queries transition to the inactive state as soon as there are no observers registered, so when all components which use that query have unmounted.
staleだけどキャッシュが残っている場合
staleなキャッシュがあるときは、それを一旦表示する
staleTimeが過ぎていたら再フェッチも走らせる
再フェッチした結果が異なる場合、再レンダリングする
cachetimeを過ぎている場合
キャッシュがないのでfallbackする(初回表示とおなじ挙動)
ただし、「表示されている(マウントされている)コンポーネントに使われているクエリ(active/inactive)」っていう概念があるので、cacheTimeはinactiveになって何秒、という感じで計算されるっぽい?