Skip to content

fix: sync cache only on compare returns true #907

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 2 commits into from
Mar 5, 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
2 changes: 1 addition & 1 deletion src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,6 @@ function useSWR<Data = any, Error = any>(
return false
}

cache.set(key, newData)
cache.set(keyErr, undefined)
cache.set(keyValidating, false)

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

// merge the new state
Expand Down
12 changes: 8 additions & 4 deletions test/use-swr-refresh.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { act, fireEvent, render, screen } from '@testing-library/react'
import React, { useState } from 'react'
import useSWR from '../src'
import useSWR, { cache } from '../src'
import { sleep } from './utils'

describe('useSWR - refresh', () => {
Expand Down Expand Up @@ -201,15 +201,16 @@ describe('useSWR - refresh', () => {
)
})

it('should allow use custom isEqual method', async () => {
it('should allow use custom compare method', async () => {
let count = 0
const key = 'dynamic-11'
const fetcher = jest.fn(() => ({
timestamp: ++count,
version: '1.0'
}))
function Page() {
const { data, mutate: change } = useSWR('dynamic-11', fetcher, {
compare: function isEqual(a, b) {
const { data, mutate: change } = useSWR(key, fetcher, {
compare: function compare(a, b) {
if (a === b) {
return true
}
Expand Down Expand Up @@ -244,6 +245,9 @@ describe('useSWR - refresh', () => {
timestamp: 2,
version: '1.0'
})

const cachedData = cache.get(key)
expect(cachedData.timestamp.toString()).toEqual('1')
expect(container.firstChild.textContent).toMatchInlineSnapshot(`"1"`)
})

Expand Down