Skip to content

fix: Fix dependency tracking and useSES bug #2576

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 7 commits into from
Apr 23, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
33 changes: 19 additions & 14 deletions core/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,32 +102,29 @@ export const useSWRHandler = <Data = any, Error = any>(
>(cache, key)

const stateDependencies = useRef<StateDependencies>({}).current

const fallback = isUndefined(fallbackData)
? config.fallback[key]
: fallbackData

const isEqual = (prev: State<Data, any>, current: State<Data, any>) => {
let equal = true
for (const _ in stateDependencies) {
const t = _ as keyof StateDependencies
if (t === 'data') {
if (!compare(current[t], prev[t])) {
if (isUndefined(prev[t])) {
if (!compare(current[t], returnedData)) {
equal = false
}
} else {
equal = false
if (!compare(prev[t], current[t])) {
if (!isUndefined(prev[t])) {
return false
}
if (!compare(returnedData, current[t])) {
return false
}
}
} else {
if (current[t] !== prev[t]) {
equal = false
return false
}
}
}
return equal
return true
}

const getSnapshot = useMemo(() => {
Expand Down Expand Up @@ -174,9 +171,17 @@ export const useSWRHandler = <Data = any, Error = any>(
return [
() => {
const newSnapshot = getSelectedCache(getCache())
return isEqual(newSnapshot, memorizedSnapshot)
? memorizedSnapshot
: (memorizedSnapshot = newSnapshot)
const compareResult = isEqual(newSnapshot, memorizedSnapshot)
if (compareResult) {
memorizedSnapshot.data = newSnapshot.data
memorizedSnapshot.isLoading = newSnapshot.isLoading
memorizedSnapshot.isValidating = newSnapshot.isValidating
memorizedSnapshot.error = newSnapshot.error
return memorizedSnapshot
} else {
memorizedSnapshot = newSnapshot
return newSnapshot
}
},
() => serverSnapshot
]
Expand Down
62 changes: 45 additions & 17 deletions examples/basic/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,49 @@
import Link from 'next/link'
import fetch from '../libs/fetch'
// import Link from 'next/link'
// import fetch from '../libs/fetch'

// import useSWR from 'swr'

// export default function Index() {
// const { data } = useSWR('/api/data', fetch)

// return (
// <div style={{ textAlign: 'center' }}>
// <h1>Trending Projects</h1>
// <div>
// {
// data ? data.map(project =>
// <p key={project}><Link href='/[user]/[repo]' as={`/${project}`}>{project}</Link></p>
// ) : 'loading...'
// }
// </div>
// </div>
// )
// }

import useSWR from 'swr'
import React, { useState, useEffect } from 'react'

const sleep = ms =>
new Promise(resolve => {
setTimeout(() => resolve('foo'), ms)
})

export default function App() {
const [state, setState] = useState(false)
useEffect(() => {
let timeout = setTimeout(() => {
setState(true)
}, 2000)
return () => {
clearTimeout(timeout)
}
}, [])

const joke = useSWR('joke', () => sleep(1000))

if (!state || !joke.data) {
return <div>loading</div>
}

export default function Index() {
const { data } = useSWR('/api/data', fetch)

return (
<div style={{ textAlign: 'center' }}>
<h1>Trending Projects</h1>
<div>
{
data ? data.map(project =>
<p key={project}><Link href='/[user]/[repo]' as={`/${project}`}>{project}</Link></p>
) : 'loading...'
}
</div>
</div>
)
return <div>{joke.data}</div>
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
"@type-challenges/utils": "0.1.1",
"@types/jest": "^29.4.0",
"@types/node": "^18.11.18",
"@types/react": "^18.0.27",
"@types/react": "^18.0.38",
"@types/use-sync-external-store": "^0.0.3",
"@typescript-eslint/eslint-plugin": "5.49.0",
"@typescript-eslint/parser": "5.49.0",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 32 additions & 0 deletions test/use-swr-integration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -592,4 +592,36 @@ describe('useSWR', () => {
]
`)
})

// Test for https://github.com/vercel/swr/issues/2446
it('should return latest data synchronously after accessing getter', async () => {
const fetcher = async () => {
await sleep(10)
return 'value'
}
const key = createKey()

const logs = []

function Page() {
const swr = useSWR(key, fetcher)
const [show, setShow] = useState(false)
useEffect(() => {
setTimeout(() => {
setShow(true)
}, 100)
}, [])
if (!show) return null
logs.push(swr.data)
return <p>data:{swr.data}</p>
}

renderWithConfig(<Page />)
await screen.findByText('data:value')
expect(logs).toMatchInlineSnapshot(`
[
"value",
]
`)
})
})
20 changes: 10 additions & 10 deletions test/use-swr-refresh.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -308,25 +308,25 @@ describe('useSWR - refresh', () => {
},
],
[
undefined,
{
"timestamp": 1,
"version": "1.0",
},
undefined,
],
[
undefined,
{
"timestamp": 1,
"version": "1.0",
},
undefined,
],
[
undefined,
{
"timestamp": 1,
"version": "1.0",
},
undefined,
],
[
{
Expand Down Expand Up @@ -377,25 +377,25 @@ describe('useSWR - refresh', () => {
},
],
[
undefined,
{
"timestamp": 1,
"version": "1.0",
},
undefined,
],
[
undefined,
{
"timestamp": 1,
"version": "1.0",
},
undefined,
],
[
undefined,
{
"timestamp": 1,
"version": "1.0",
},
undefined,
],
[
{
Expand Down Expand Up @@ -449,21 +449,21 @@ describe('useSWR - refresh', () => {
],
[
{
"timestamp": 2,
"timestamp": 1,
"version": "1.0",
},
{
"timestamp": 1,
"timestamp": 2,
"version": "1.0",
},
],
[
{
"timestamp": 1,
"timestamp": 2,
"version": "1.0",
},
{
"timestamp": 2,
"timestamp": 1,
"version": "1.0",
},
],
Expand Down