Skip to content

fix #1056 #1058

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

Merged
merged 3 commits into from
Mar 22, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,9 +470,11 @@ function useSWR<Data = any, Error = any>(
// deep compare to avoid extra re-render
// data changed
newState.data = newData
cache.set(key, newData)
}

if (!config.compare(cache.get(key), newData)) {
cache.set(key, newData)
}
// merge the new state
dispatch(newState)

Expand Down
33 changes: 31 additions & 2 deletions test/use-swr-suspense.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { act, render, screen } from '@testing-library/react'
import { act, fireEvent, render, screen } from '@testing-library/react'
import React, { ReactNode, Suspense, useEffect, useState } from 'react'
import useSWR, { mutate } from '../src'
import { sleep } from './utils'
import { createResponse, sleep } from './utils'

class ErrorBoundary extends React.Component<{ fallback: ReactNode }> {
state = { hasError: false }
Expand Down Expand Up @@ -192,6 +192,35 @@ describe('useSWR - suspense', () => {
expect(renderedResults).toEqual(['suspense-7', 'suspense-8'])
})

it('should render correctly when key changes (but with same response data)', async () => {
// https://github.com/vercel/swr/issues/1056
const renderedResults = []
function Section() {
const [key, setKey] = useState(1)
const { data } = useSWR(`foo?a=${key}`, () => createResponse('123'), {
suspense: true
})
if (`${data},${key}` !== renderedResults[renderedResults.length - 1]) {
renderedResults.push(`${data},${key}`)
}
return <div onClick={() => setKey(v => v + 1)}>{`${data},${key}`}</div>
}

render(
<Suspense fallback={<div>fallback</div>}>
<Section />
</Suspense>
)

await screen.findByText('123,1')

fireEvent.click(screen.getByText('123,1'))

await screen.findByText('123,2')

expect(renderedResults).toEqual(['123,1', '123,2'])
})

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

Expand Down