|
1 | 1 | import { act, screen, fireEvent } from '@testing-library/react' |
2 | | -import React, { useState, useEffect } from 'react' |
| 2 | +import React, { useState, useEffect, Profiler } from 'react' |
3 | 3 | import useSWR from 'swr' |
4 | 4 | import { |
5 | 5 | createResponse, |
@@ -432,4 +432,40 @@ describe('useSWR', () => { |
432 | 432 | await act(() => sleep(20)) |
433 | 433 | screen.getByText('data: 1') |
434 | 434 | }) |
| 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 | + }) |
435 | 471 | }) |
0 commit comments