Skip to content
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
6 changes: 4 additions & 2 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,11 @@ const mutate: mutateInterface = async (
promises.push(updaters[i](!!shouldRevalidate, data, error, i > 0))
}
// return new updated value
return Promise.all(promises).then(() => cache.get(key))
return Promise.all(promises).then(() => {
if (error) throw error
return cache.get(key)
})
}

// throw error or return data to be used by caller of mutate
if (error) throw error
return data
Expand Down
31 changes: 21 additions & 10 deletions test/use-swr.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1292,7 +1292,7 @@ describe('useSWR - local mutation', () => {
})

it('should update error in cache when mutate failed with error', async () => {
let value = 0
const value = 0
const key = 'mutate-4'
const message = 'mutate-error'
function Page() {
Expand All @@ -1303,21 +1303,32 @@ describe('useSWR - local mutation', () => {
await waitForDomChange({ container })
expect(container.firstChild.textContent).toMatchInlineSnapshot(`"data: 0"`)
await act(async () => {
await mutate(
key,
() => {
throw new Error(message)
},
false
)
// mutate error will be thrown, add try catch to avoid crashing
try {
await mutate(
key,
() => {
throw new Error(message)
},
false
)
} catch (e) {
// do nothing
}
})

const [, , keyErr] = cache.serializeKey(key)
const error = cache.get(keyErr)
expect(error.message).toMatchInlineSnapshot(`"${message}"`)
let cacheError = cache.get(keyErr)
expect(cacheError.message).toMatchInlineSnapshot(`"${message}"`)
expect(container.firstChild.textContent).toMatchInlineSnapshot(
`"${message}"`
)
// if mutate succeed, error should be cleared
await act(async () => {
await mutate(key, value, false)
})
cacheError = cache.get(keyErr)
expect(cacheError).toMatchInlineSnapshot(`undefined`)
})
})

Expand Down