Skip to content

Commit

Permalink
fix: Avoid preloading the resource multiple times (#2036)
Browse files Browse the repository at this point in the history
fix: Avoid preloading multiple times
  • Loading branch information
shuding committed Jun 18, 2022
1 parent cb05828 commit 790e044
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
8 changes: 6 additions & 2 deletions _internal/utils/preload.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { Middleware, Key, BareFetcher, GlobalState } from '../types'
import type { Middleware, Key, BareFetcher, GlobalState } from '../types'
import { serialize } from './serialize'
import { cache } from './config'
import { SWRGlobalState } from './global-state'

export const preload = <Data = any>(key_: Key, fetcher: BareFetcher<Data>) => {
const req = fetcher(key_)
const key = serialize(key_)[0]
const [, , , PRELOAD] = SWRGlobalState.get(cache) as GlobalState

// Prevent preload to be called multiple times before used.
if (PRELOAD[key]) return PRELOAD[key]

const req = fetcher(key_)
PRELOAD[key] = req
return req
}
Expand Down
24 changes: 24 additions & 0 deletions test/use-swr-preload.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,30 @@ describe('useSWR - preload', () => {
expect(count).toBe(1)
})

it('should avoid preloading the resource multiple times', async () => {
const key = createKey()
let count = 0

const fetcher = () => {
++count
return createResponse('foo')
}

function Page() {
const { data } = useSWR(key, fetcher)
return <div>data:{data}</div>
}

preload(key, fetcher)
preload(key, fetcher)
preload(key, fetcher)
expect(count).toBe(1)

renderWithConfig(<Page />)
await screen.findByText('data:foo')
expect(count).toBe(1)
})

it('preload the fetcher function with the suspense mode', async () => {
const key = createKey()
let count = 0
Expand Down

0 comments on commit 790e044

Please sign in to comment.