Skip to content

Commit d676bb9

Browse files
authored
test: add test case for vercel#1974 (vercel#2005)
1 parent 7aaf5be commit d676bb9

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

core/use-swr.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,6 @@ export const useSWRHandler = <Data = any, Error = any>(
278278
}
279279
try {
280280
if (shouldStartNewRequest) {
281-
// TODO: should add a test case for this https://github.com/vercel/swr/issues/1974
282281
setCache(initialState)
283282
// If no cache being rendered currently (it shows a blank page),
284283
// we trigger the loading slow event.

test/use-swr-integration.test.tsx

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { act, screen, fireEvent } from '@testing-library/react'
2-
import React, { useState, useEffect } from 'react'
2+
import React, { useState, useEffect, Profiler } from 'react'
33
import useSWR from 'swr'
44
import {
55
createResponse,
@@ -432,4 +432,40 @@ describe('useSWR', () => {
432432
await act(() => sleep(20))
433433
screen.getByText('data: 1')
434434
})
435+
it('Nested SWR hook should only do loading once', async () => {
436+
const key = createKey()
437+
let count = 0
438+
const ChildComponent = () => {
439+
const { data } = useSWR(key, (_) => createResponse(_, { delay: 100 }))
440+
return (
441+
<div id="child">
442+
{data}
443+
</div>
444+
)
445+
}
446+
const NestedRender = () => {
447+
const { data, isValidating } = useSWR(key, (_) => createResponse(_, { delay: 50 }))
448+
if (isValidating) {
449+
return <div>loading</div>
450+
}
451+
return (
452+
<div>
453+
<div id="parent">{data}</div>
454+
<ChildComponent></ChildComponent>
455+
</div>
456+
)
457+
}
458+
const Page = () => (
459+
<Profiler id={key} onRender={() => {
460+
count += 1
461+
}}>
462+
<NestedRender></NestedRender>
463+
</Profiler>
464+
)
465+
renderWithConfig(<Page />)
466+
await screen.findByText(`loading`)
467+
await screen.findAllByText(key)
468+
await act(() => sleep(150))
469+
expect(count).toBe(2)
470+
})
435471
})

0 commit comments

Comments
 (0)