Skip to content

Commit e3d4248

Browse files
authored
should treat key change as remount (#1430)
1 parent 20c02df commit e3d4248

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/use-swr.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ export const useSWRHandler = <Data = any, Error = any>(
400400
}
401401

402402
// Trigger a revalidation.
403-
if (keyChanged || shouldRevalidateOnMount()) {
403+
if (shouldRevalidateOnMount()) {
404404
if (isUndefined(data) || IS_SERVER) {
405405
// Revalidate immediately.
406406
softRevalidate()

test/use-swr-immutable.test.tsx

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,4 +138,56 @@ describe('useSWR - immutable', () => {
138138
await act(() => sleep(50))
139139
await screen.findByText('data: 0')
140140
})
141+
142+
it('should not revalidate with revalidateIfStale disabled when key changes', async () => {
143+
const fetcher = jest.fn(v => {
144+
console.log(v)
145+
return v
146+
})
147+
148+
const key = createKey()
149+
const useData = (id: string) =>
150+
useSWR(key + id, fetcher, {
151+
dedupingInterval: 0,
152+
revalidateIfStale: false
153+
})
154+
155+
function Page() {
156+
const [id, setId] = useState('0')
157+
const { data } = useData(id)
158+
return (
159+
<button onClick={() => setId(id === '0' ? '1' : '0')}>
160+
data: {data}
161+
</button>
162+
)
163+
}
164+
165+
render(<Page />)
166+
167+
// Ready
168+
await screen.findByText(`data: ${key}0`)
169+
170+
// Toggle key by clicking the button
171+
fireEvent.click(screen.getByText(`data: ${key}0`))
172+
await screen.findByText(`data: ${key}1`)
173+
174+
await waitForNextTick()
175+
176+
// Toggle key again by clicking the button
177+
fireEvent.click(screen.getByText(`data: ${key}1`))
178+
await screen.findByText(`data: ${key}0`)
179+
180+
await waitForNextTick()
181+
182+
// Toggle key by clicking the button
183+
fireEvent.click(screen.getByText(`data: ${key}0`))
184+
await screen.findByText(`data: ${key}1`)
185+
186+
await sleep(20)
187+
188+
// `fetcher` should only be called twice, with each key.
189+
expect(fetcher).toBeCalledTimes(2)
190+
expect(fetcher).nthCalledWith(1, key + '0')
191+
expect(fetcher).nthCalledWith(2, key + '1')
192+
})
141193
})

0 commit comments

Comments
 (0)