Skip to content

Commit

Permalink
enhance: fallback to setTimeout when request idle callback is not ava…
Browse files Browse the repository at this point in the history
…ilable (#473)

* enhance: polyfill irc (#471)

* run timers

* fix tests
  • Loading branch information
huozhi committed Jul 25, 2020
1 parent 89adb2b commit 2a16045
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
13 changes: 7 additions & 6 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ import {

const IS_SERVER = typeof window === 'undefined'

// polyfill for requestIdleCallback
const rIC = IS_SERVER
? null
: window['requestIdleCallback'] || (f => setTimeout(f, 1))

// React currently throws a warning when using useLayoutEffect on the server.
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser.
Expand Down Expand Up @@ -437,14 +442,10 @@ function useSWR<Data = any, Error = any>(
config.revalidateOnMount ||
(!config.initialData && config.revalidateOnMount === undefined)
) {
if (
typeof latestKeyedData !== 'undefined' &&
!IS_SERVER &&
window['requestIdleCallback']
) {
if (typeof latestKeyedData !== 'undefined') {
// delay revalidate if there's cache
// to not block the rendering
window['requestIdleCallback'](softRevalidate)
rIC(softRevalidate)
} else {
softRevalidate()
}
Expand Down
3 changes: 2 additions & 1 deletion test/use-swr.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ describe('useSWR', () => {
return <div>hello, {data}</div>
}

render(<Page />)
const { container } = render(<Page />)
await waitForDomChange({ container })
expect(fetch).toHaveBeenCalled()
})

Expand Down

0 comments on commit 2a16045

Please sign in to comment.