Skip to content

Commit 21fe398

Browse files
huozhishuding
andauthored
fix: sync cache only on compare returns true (#907)
Co-authored-by: Shu Ding <[email protected]>
1 parent 66aaefd commit 21fe398

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
@@ -464,7 +464,6 @@ function useSWR<Data = any, Error = any>(
464464
return false
465465
}
466466

467-
cache.set(key, newData)
468467
cache.set(keyErr, undefined)
469468
cache.set(keyValidating, false)
470469

@@ -481,6 +480,7 @@ function useSWR<Data = any, Error = any>(
481480
// deep compare to avoid extra re-render
482481
// data changed
483482
newState.data = newData
483+
cache.set(key, newData)
484484
}
485485

486486
// 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)