diff --git a/src/use-swr.ts b/src/use-swr.ts index fd57d4a108..a0a9218983 100644 --- a/src/use-swr.ts +++ b/src/use-swr.ts @@ -545,13 +545,9 @@ function useSWR( // need to start the request if it hasn't if (!CONCURRENT_PROMISES[key]) { - if (key) { - // trigger revalidate immediately - // to get the promise - revalidate() - } else { - throw Promise.reject() - } + // trigger revalidate immediately + // to get the promise + revalidate() } if ( @@ -571,6 +567,10 @@ function useSWR( throw latestError } + if (!key) { + throw new Promise(() => {}) + } + // return the latest data / error from cache // in case `key` has changed return { diff --git a/test/use-swr.test.tsx b/test/use-swr.test.tsx index e7e28ef01b..9f56ca4968 100644 --- a/test/use-swr.test.tsx +++ b/test/use-swr.test.tsx @@ -1270,30 +1270,31 @@ describe('useSWR - suspense', () => { // hold render when suspense it('should pause when key is falsy', async () => { - function SectionContent({ swrKey, onClick }) { + function SectionContent({ swrKey }) { const { data } = useSWR( - () => (swrKey % 2 === 0 ? null : swrKey), - k => new Promise(res => setTimeout(() => res(k), 30)), + () => (swrKey % 2 ? null : 'suspense-' + swrKey), + key => + new Promise(res => + setTimeout(() => res(key.replace('suspense-', '')), 100) + ), { suspense: true } ) - return ( -
- {swrKey && data ? 'suspense-' + (9 + Number(data)) : undefined} -
- ) + return
{data}
} const Section = () => { - const [key, setKey] = useState(0) + const [key, setKey] = useState(9) const handleClick = () => setKey(key + 1) return ( - fallback}> - - +
+ fallback
}> + + + ) } @@ -1306,13 +1307,21 @@ describe('useSWR - suspense', () => { ) } - expect(container.textContent).toMatchInlineSnapshot(`"fallback"`) - await clickAndWait(100) - expect(container.textContent).toMatchInlineSnapshot(`"suspense-10"`) - await clickAndWait(100) - expect(container.textContent).toMatchInlineSnapshot(`"fallback"`) - await clickAndWait(100) - expect(container.textContent).toMatchInlineSnapshot(`"suspense-10"`) + expect( + container.firstElementChild.lastElementChild.textContent + ).toMatchInlineSnapshot(`"fallback"`) + await clickAndWait(150) + expect( + container.firstElementChild.lastElementChild.textContent + ).toMatchInlineSnapshot(`"10"`) + await clickAndWait(150) + expect( + container.firstElementChild.lastElementChild.textContent + ).toMatchInlineSnapshot(`"fallback"`) + await clickAndWait(150) + expect( + container.firstElementChild.lastElementChild.textContent + ).toMatchInlineSnapshot(`"12"`) }) })