Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/_internal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export { getTimestamp } from './utils/timestamp'
export { useSWRConfig } from './utils/use-swr-config'
export { preset, defaultConfigOptions } from './utils/web-preset'
export { withMiddleware } from './utils/with-middleware'
export { preload } from './utils/preload'
export { preload, clearPreloadCache } from './utils/preload'

export * from './types'

Expand Down
7 changes: 7 additions & 0 deletions src/_internal/utils/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ export const preload = <
return req
}

export const clearPreloadCache = () => {
const globalState = SWRGlobalState.get(cache) as GlobalState

// index 3 are PRELOAD
globalState[3] = Object.create(null)
}

export const middleware: Middleware =
useSWRNext => (key_, fetcher_, config) => {
// fetcher might be a sync function, so this should not be an async function
Expand Down
2 changes: 1 addition & 1 deletion src/index/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export { SWRConfig } from './use-swr'
export { unstable_serialize } from './serialize'
export { useSWRConfig } from '../_internal'
export { mutate } from '../_internal'
export { preload } from '../_internal'
export { preload, clearPreloadCache } from '../_internal'

// Config

Expand Down
22 changes: 21 additions & 1 deletion test/use-swr-preload.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { act, fireEvent, screen } from '@testing-library/react'
import { Suspense, useEffect, useState, Profiler } from 'react'
import useSWR, { preload, useSWRConfig } from 'swr'
import useSWR, { preload, clearPreloadCache, useSWRConfig } from 'swr'
import {
createKey,
createResponse,
Expand Down Expand Up @@ -224,4 +224,24 @@ describe('useSWR - preload', () => {
preload(() => key, fetcher)
expect(calledWith).toBe(key)
})

it('re-call fetcher when preload cache are cleared', async () => {
const key = createKey()

const fetcher = jest.fn(() => createResponse('foo'))

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

preload(key, fetcher)
expect(fetcher).toBeCalledTimes(1)

clearPreloadCache()

renderWithGlobalCache(<Page />)
await screen.findByText('data:foo')
expect(fetcher).toBeCalledTimes(2)
})
})