Skip to content

Commit c5df6a5

Browse files
authored
fix: should throw when mutate failed (vercel#557)
1 parent 4bae43f commit c5df6a5

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

src/use-swr.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,9 +139,11 @@ const mutate: mutateInterface = async (
139139
promises.push(updaters[i](!!shouldRevalidate, data, error, i > 0))
140140
}
141141
// return new updated value
142-
return Promise.all(promises).then(() => cache.get(key))
142+
return Promise.all(promises).then(() => {
143+
if (error) throw error
144+
return cache.get(key)
145+
})
143146
}
144-
145147
// throw error or return data to be used by caller of mutate
146148
if (error) throw error
147149
return data

test/use-swr.test.tsx

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1292,7 +1292,7 @@ describe('useSWR - local mutation', () => {
12921292
})
12931293

12941294
it('should update error in cache when mutate failed with error', async () => {
1295-
let value = 0
1295+
const value = 0
12961296
const key = 'mutate-4'
12971297
const message = 'mutate-error'
12981298
function Page() {
@@ -1303,21 +1303,32 @@ describe('useSWR - local mutation', () => {
13031303
await waitForDomChange({ container })
13041304
expect(container.firstChild.textContent).toMatchInlineSnapshot(`"data: 0"`)
13051305
await act(async () => {
1306-
await mutate(
1307-
key,
1308-
() => {
1309-
throw new Error(message)
1310-
},
1311-
false
1312-
)
1306+
// mutate error will be thrown, add try catch to avoid crashing
1307+
try {
1308+
await mutate(
1309+
key,
1310+
() => {
1311+
throw new Error(message)
1312+
},
1313+
false
1314+
)
1315+
} catch (e) {
1316+
// do nothing
1317+
}
13131318
})
13141319

13151320
const [, , keyErr] = cache.serializeKey(key)
1316-
const error = cache.get(keyErr)
1317-
expect(error.message).toMatchInlineSnapshot(`"${message}"`)
1321+
let cacheError = cache.get(keyErr)
1322+
expect(cacheError.message).toMatchInlineSnapshot(`"${message}"`)
13181323
expect(container.firstChild.textContent).toMatchInlineSnapshot(
13191324
`"${message}"`
13201325
)
1326+
// if mutate succeed, error should be cleared
1327+
await act(async () => {
1328+
await mutate(key, value, false)
1329+
})
1330+
cacheError = cache.get(keyErr)
1331+
expect(cacheError).toMatchInlineSnapshot(`undefined`)
13211332
})
13221333
})
13231334

0 commit comments

Comments
 (0)