diff --git a/src/use-swr.ts b/src/use-swr.ts index 113e52f5c..53573f00b 100644 --- a/src/use-swr.ts +++ b/src/use-swr.ts @@ -97,13 +97,14 @@ export const useSWRHandler = ( // If it's paused, we skip revalidation. if (getConfig().isPaused()) return false - return suspense - ? // Under suspense mode, it will always fetch on render if there is no - // stale data so no need to revalidate immediately on mount again. - !isUndefined(data) - : // If there is no stale data, we need to revalidate on mount; - // If `revalidateIfStale` is set to true, we will always revalidate. - isUndefined(data) || config.revalidateIfStale + // Under suspense mode, it will always fetch on render if there is no + // stale data so no need to revalidate immediately on mount again. + // If data exists, only revalidate if `revalidateIfStale` is true. + if (suspense) return isUndefined(data) ? false : config.revalidateIfStale + + // If there is no stale data, we need to revalidate on mount; + // If `revalidateIfStale` is set to true, we will always revalidate. + return isUndefined(data) || config.revalidateIfStale } // Resolve the current validating state. diff --git a/test/use-swr-suspense.test.tsx b/test/use-swr-suspense.test.tsx index c1a327100..321bb6a58 100644 --- a/test/use-swr-suspense.test.tsx +++ b/test/use-swr-suspense.test.tsx @@ -163,6 +163,31 @@ describe('useSWR - suspense', () => { await screen.findByText('hello, error') // get error with cache }) + it('should not fetch when cached data is present and `revalidateIfStale` is false', async () => { + const key = createKey() + mutate(key, 'cached') + + let fetchCount = 0 + + function Section() { + const { data } = useSWR(key, () => createResponse(++fetchCount), { + suspense: true, + revalidateIfStale: false + }) + return
{data}
+ } + + renderWithGlobalCache( + fallback}> +
+ + ) + + screen.getByText('cached') + await act(() => sleep(50)) // Wait to confirm fetch is not triggered + expect(fetchCount).toBe(0) + }) + it('should pause when key changes', async () => { const renderedResults = [] const initialKey = createKey()