Skip to content

Commit

Permalink
fix: reset stale unmountedRef in suspense (#1843)
Browse files Browse the repository at this point in the history
  • Loading branch information
promer94 committed Feb 6, 2022
1 parent 01e0594 commit f98da66
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,7 @@ export const useSWRHandler = <Data = any, Error = any>(
// Always update fetcher and config refs even with the Suspense mode.
fetcherRef.current = fetcher
configRef.current = config
unmountedRef.current = false
throw isUndefined(error) ? revalidate(WITH_DEDUPE) : error
}

Expand Down
55 changes: 55 additions & 0 deletions test/use-swr-suspense.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,61 @@ describe('useSWR - suspense', () => {
expect(renderedResults).toEqual(['123,1', '123,2'])
})

it('should render correctly when key changes (from null to valid key)', async () => {
// https://github.com/vercel/swr/issues/1836
const renderedResults = []
const baseKey = createKey()
let setData: any = () => {}
const Result = ({ query }: { query: string }) => {
const { data } = useSWR(
query ? `${baseKey}-${query}` : null,
key => createResponse(key, { delay: 200 }),
{
suspense: true
}
)
if (`${data}` !== renderedResults[renderedResults.length - 1]) {
if (data === undefined) {
renderedResults.push(`${baseKey}-nodata`)
} else {
renderedResults.push(`${data}`)
}
}
return <div>{data ? data : `${baseKey}-nodata`}</div>
}
const App = () => {
const [query, setQuery] = useState('123')
if (setData !== setQuery) {
setData = setQuery
}
return (
<>
<br />
<br />
<Suspense fallback={null}>
<Result query={query}></Result>
</Suspense>
</>
)
}

renderWithConfig(<App />)

await screen.findByText(`${baseKey}-123`)

act(() => setData(''))
await screen.findByText(`${baseKey}-nodata`)

act(() => setData('456'))
await screen.findByText(`${baseKey}-456`)

expect(renderedResults).toEqual([
`${baseKey}-123`,
`${baseKey}-nodata`,
`${baseKey}-456`
])
})

it('should render initial data if set', async () => {
const fetcher = jest.fn(() => 'SWR')

Expand Down

0 comments on commit f98da66

Please sign in to comment.