Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: suspense when key is falsy #357

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ function useSWR<Data = any, Error = any>(

// update the state if the key changed (not the inital render) or cache updated
if (
keyRef.current !== key ||
(keyRef.current !== key && (!keyRef.current && !key)) ||
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t know why the tests passed, but shouldn’t this be

(keyRef.current && key)

?

However it still confuses me that when key is falsy, the effect will end early from line 361.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good catch here. the previous test didn't really match the behavior so I removed it. I thought the condition was missed there but actually line 361 has already filtered it out.

!config.compare(currentHookData, latestKeyedData)
) {
dispatch({ data: latestKeyedData })
Expand Down
34 changes: 34 additions & 0 deletions test/use-swr.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,40 @@ describe('useSWR - suspense', () => {
// 'suspense-7' -> undefined -> 'suspense-8'
expect(renderedResults).toEqual(['suspense-7', 'suspense-8'])
})

// hold render when suspense
it('should pause when key is falsy', async () => {
const renderedResults = []

function Section() {
const [key, setKey] = useState(null)
const { data } = useSWR(
key,
k => new Promise(res => setTimeout(() => res(k), 50)),
{
suspense: true
}
)

useEffect(() => {
setKey('suspense-9')
}, [])

if (data !== renderedResults[renderedResults.length - 1]) {
renderedResults.push(data)
}

return <div>{data}</div>
}
render(
<Suspense fallback={<div>fallback</div>}>
<Section />
</Suspense>
)
await act(() => new Promise(res => setTimeout(res, 210)))

expect(renderedResults).toEqual(['suspense-9'])
})
})

describe('useSWR - cache', () => {
Expand Down