diff --git a/src/use-swr.ts b/src/use-swr.ts index 2bd493997..798f3efc3 100644 --- a/src/use-swr.ts +++ b/src/use-swr.ts @@ -276,14 +276,25 @@ function useSWR( fn = config.fetcher } + const willRevalidateOnMount = () => { + return ( + config.revalidateOnMount || + (!config.initialData && config.revalidateOnMount === undefined) + ) + } + const resolveData = () => { const cachedData = cache.get(key) return typeof cachedData === 'undefined' ? config.initialData : cachedData } + const resolveIsValidating = () => { + return !!cache.get(keyValidating) || (key && willRevalidateOnMount()) + } + const initialData = resolveData() const initialError = cache.get(keyErr) - const initialIsValidating = !!cache.get(keyValidating) + const initialIsValidating = resolveIsValidating() // if a state is accessed (data, error or isValidating), // we add the state to dependencies so if the state is @@ -590,10 +601,7 @@ function useSWR( const softRevalidate = () => revalidate({ dedupe: true }) // trigger a revalidation - if ( - config.revalidateOnMount || - (!config.initialData && config.revalidateOnMount === undefined) - ) { + if (willRevalidateOnMount()) { if (typeof latestKeyedData !== 'undefined' && !IS_SERVER) { // delay revalidate if there's cache // to not block the rendering diff --git a/test/use-swr-loading.test.tsx b/test/use-swr-loading.test.tsx index fef1dec55..b3f736aaa 100644 --- a/test/use-swr-loading.test.tsx +++ b/test/use-swr-loading.test.tsx @@ -24,10 +24,9 @@ describe('useSWR - loading', () => { await act(() => sleep(110)) expect(container.textContent).toMatchInlineSnapshot(`"hello, data, ready"`) // data isValidating - // -> undefined, false // -> undefined, true // -> data, false - expect(renderCount).toEqual(3) + expect(renderCount).toEqual(2) }) it('should avoid extra rerenders', async () => {