Skip to content

Commit

Permalink
fix: not clear promise of revalidate after mutating
Browse files Browse the repository at this point in the history
  • Loading branch information
MoonBall committed Apr 26, 2021
1 parent f787624 commit 800a882
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ async function mutate<Data = any>(
// enter the revalidation stage
// update existing SWR Hooks' state
const updaters = CACHE_REVALIDATORS[key]
if (updaters) {
if (updaters && updaters.length) {
const promises = []
for (let i = 0; i < updaters.length; ++i) {
promises.push(
Expand All @@ -180,6 +180,11 @@ async function mutate<Data = any>(
if (error) throw error
return cache.get(key)
})
} else if (shouldRevalidate) {
// `updaters` would trigger revalidate if `updaters.length > 0`.
// So clear promise of revalidate if `!updaters.length && shouldRevalidate`
delete CONCURRENT_PROMISES[key]
delete CONCURRENT_PROMISES_TS[key]
}
// throw error or return data to be used by caller of mutate
if (error) throw error
Expand Down
52 changes: 50 additions & 2 deletions test/use-swr-revalidate.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 from 'react'
import useSWR from '../src'
import React, { useEffect, useState } from 'react'
import useSWR, { mutate } from '../src'
import { createResponse, sleep } from './utils'

const waitForNextTick = () => act(() => sleep(1))
Expand Down Expand Up @@ -136,4 +136,52 @@ describe('useSWR - revalidate', () => {
await act(() => sleep(70))
screen.getByText('count: 2')
})

it('cg test', async () => {
const swrKey = 'cg test'
function A() {
const { data } = useSWR(
swrKey,
async () => {
return 'A'
},
{
dedupingInterval: 6000
}
)
return <>{data}</>
}

function B() {
useEffect(() => {
mutate(swrKey, async () => {
return 'B'
})
}, [])
return null
}

function Page() {
const [isShowA, setIsShowA] = useState(true)

return (
<button
onClick={() => {
setIsShowA(!isShowA)
}}
>
click me {isShowA ? <A /> : <B />}
</button>
)
}

render(<Page />)

await act(() => sleep(20))
fireEvent.click(screen.getByText('click me A'))
await act(() => sleep(20))
fireEvent.click(screen.getByText('click me'))
await act(() => sleep(20))
screen.getByText('click me A')
})
})

0 comments on commit 800a882

Please sign in to comment.