Skip to content

Commit 696bc5c

Browse files
authored
fix race condition and add test (#261)
1 parent 3c9ebe8 commit 696bc5c

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/use-swr.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -275,13 +275,13 @@ function useSWR<Data = any, Error = any>(
275275

276276
CONCURRENT_PROMISES_TS[key] = startAt = Date.now()
277277

278+
newData = await CONCURRENT_PROMISES[key]
279+
278280
setTimeout(() => {
279281
delete CONCURRENT_PROMISES[key]
280282
delete CONCURRENT_PROMISES_TS[key]
281283
}, config.dedupingInterval)
282284

283-
newData = await CONCURRENT_PROMISES[key]
284-
285285
// trigger the success event,
286286
// only do this for the original request.
287287
config.onSuccess(newData, key, config)
@@ -470,7 +470,10 @@ function useSWR<Data = any, Error = any>(
470470

471471
// set up reconnecting when the browser regains network connection
472472
let reconnect = null
473-
if (typeof addEventListener !== 'undefined' && config.revalidateOnReconnect) {
473+
if (
474+
typeof addEventListener !== 'undefined' &&
475+
config.revalidateOnReconnect
476+
) {
474477
reconnect = addEventListener('online', softRevalidate)
475478
}
476479

test/use-swr.test.tsx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,6 +852,28 @@ describe('useSWR - local mutation', () => {
852852
await act(() => new Promise(res => setTimeout(res, 110)))
853853
expect(container.textContent).toMatchInlineSnapshot(`"data: 999"`)
854854
})
855+
856+
it('should ignore in flight requests when mutating', async () => {
857+
// set it to 1
858+
mutate('mutate-2', 1)
859+
860+
function Section() {
861+
const { data } = useSWR(
862+
'mutate-2',
863+
() => new Promise(res => setTimeout(() => res(2), 200))
864+
)
865+
return <div>{data}</div>
866+
}
867+
868+
const { container } = render(<Section />)
869+
870+
expect(container.textContent).toMatchInlineSnapshot(`"1"`) // directly from cache
871+
await act(() => new Promise(res => setTimeout(res, 150))) // still suspending
872+
mutate('mutate-2', 3) // set it to 3. this will drop the ongoing request
873+
expect(container.textContent).toMatchInlineSnapshot(`"3"`)
874+
await act(() => new Promise(res => setTimeout(res, 100)))
875+
expect(container.textContent).toMatchInlineSnapshot(`"3"`)
876+
})
855877
})
856878

857879
describe('useSWR - context configs', () => {

0 commit comments

Comments
 (0)