Skip to content

Commit 1d26c95

Browse files
committed
fix: sync cache only on compare returns true
1 parent d55853f commit 1d26c95

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

src/use-swr.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,6 @@ function useSWR<Data = any, Error = any>(
482482
return false
483483
}
484484

485-
cache.set(key, newData)
486485
cache.set(keyErr, undefined)
487486
cache.set(keyValidating, false)
488487

@@ -499,6 +498,7 @@ function useSWR<Data = any, Error = any>(
499498
// deep compare to avoid extra re-render
500499
// data changed
501500
newState.data = newData
501+
cache.set(key, newData)
502502
}
503503

504504
// merge the new state

test/use-swr-refresh.test.tsx

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { act, fireEvent, render, screen } from '@testing-library/react'
22
import React, { useState } from 'react'
3-
import useSWR from '../src'
3+
import useSWR, { cache } from '../src'
44
import { sleep } from './utils'
55

66
describe('useSWR - refresh', () => {
@@ -201,15 +201,16 @@ describe('useSWR - refresh', () => {
201201
)
202202
})
203203

204-
it('should allow use custom isEqual method', async () => {
204+
it('should allow use custom compare method', async () => {
205205
let count = 0
206+
const key = 'dynamic-11'
206207
const fetcher = jest.fn(() => ({
207208
timestamp: ++count,
208209
version: '1.0'
209210
}))
210211
function Page() {
211-
const { data, mutate: change } = useSWR('dynamic-11', fetcher, {
212-
compare: function isEqual(a, b) {
212+
const { data, mutate: change } = useSWR(key, fetcher, {
213+
compare: function compare(a, b) {
213214
if (a === b) {
214215
return true
215216
}
@@ -244,6 +245,9 @@ describe('useSWR - refresh', () => {
244245
timestamp: 2,
245246
version: '1.0'
246247
})
248+
249+
const cachedData = cache.get(key)
250+
expect(cachedData.timestamp.toString()).toEqual('1')
247251
expect(container.firstChild.textContent).toMatchInlineSnapshot(`"1"`)
248252
})
249253

0 commit comments

Comments
 (0)