Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Avoid preloading the resource multiple times #2036

Merged
merged 1 commit into from
Jun 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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