Skip to content

Commit db4b730

Browse files
committed
fix: sync cache only on compare returns true
1 parent 81824c7 commit db4b730

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

src/use-swr.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,6 @@ function useSWR<Data = any, Error = any>(
475475
return false
476476
}
477477

478-
cache.set(key, newData)
479478
cache.set(keyErr, undefined)
480479
cache.set(keyValidating, false)
481480

@@ -492,6 +491,7 @@ function useSWR<Data = any, Error = any>(
492491
// deep compare to avoid extra re-render
493492
// data changed
494493
newState.data = newData
494+
cache.set(key, newData)
495495
}
496496

497497
// merge the new state

test/use-swr.test.tsx

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -686,16 +686,17 @@ describe('useSWR - refresh', () => {
686686
)
687687
})
688688

689-
it('should allow use custom isEqual method', async () => {
689+
it('should allow use custom compare method', async () => {
690+
const key = 'dynamic-11'
690691
function Page() {
691692
const { data, revalidate } = useSWR(
692-
'dynamic-11',
693+
key,
693694
() => ({
694695
timestamp: +new Date(),
695696
version: '1.0'
696697
}),
697698
{
698-
compare: function isEqual(a, b) {
699+
compare: function compare(a, b) {
699700
if (a === b) {
700701
return true
701702
}
@@ -724,6 +725,9 @@ describe('useSWR - refresh', () => {
724725
return new Promise(res => setTimeout(res, 1))
725726
})
726727
const secondContent = container.firstChild.textContent
728+
const cachedData = cache.get(key)
729+
730+
expect(cachedData.timestamp.toString()).toEqual(secondContent)
727731
expect(firstContent).toEqual(secondContent)
728732
})
729733

0 commit comments

Comments
 (0)