Skip to content

Commit fee4a14

Browse files
authored
fix(mutations): allow passing a function to useErrorBoundary (#3390)
1 parent bc7263d commit fee4a14

File tree

3 files changed

+54
-3
lines changed

3 files changed

+54
-3
lines changed

src/reactjs/tests/useMutation.test.tsx

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,57 @@ describe('useMutation', () => {
659659
})
660660
})
661661

662+
it('should be able to throw an error when useErrorBoundary is a function that returns true', async () => {
663+
let boundary = false
664+
function Page() {
665+
const { mutate, error } = useMutation<string, Error>(
666+
() => {
667+
const err = new Error('mock error')
668+
err.stack = ''
669+
return Promise.reject(err)
670+
},
671+
{
672+
useErrorBoundary: () => {
673+
boundary = !boundary
674+
return !boundary
675+
},
676+
}
677+
)
678+
679+
return (
680+
<div>
681+
<button onClick={() => mutate()}>mutate</button>
682+
{error && error.message}
683+
</div>
684+
)
685+
}
686+
687+
const { getByText, queryByText } = renderWithClient(
688+
queryClient,
689+
<ErrorBoundary
690+
fallbackRender={() => (
691+
<div>
692+
<span>error boundary</span>
693+
</div>
694+
)}
695+
>
696+
<Page />
697+
</ErrorBoundary>
698+
)
699+
700+
// first error goes to component
701+
fireEvent.click(getByText('mutate'))
702+
await waitFor(() => {
703+
expect(queryByText('mock error')).not.toBeNull()
704+
})
705+
706+
// second error goes to boundary
707+
fireEvent.click(getByText('mutate'))
708+
await waitFor(() => {
709+
expect(queryByText('error boundary')).not.toBeNull()
710+
})
711+
})
712+
662713
it('should pass meta to mutation', async () => {
663714
const errorMock = jest.fn()
664715
const successMock = jest.fn()

src/reactjs/useMutation.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ export function useMutation<
116116

117117
if (
118118
currentResult.error &&
119-
shouldThrowError(!!obsRef.current.options.useErrorBoundary, [
119+
shouldThrowError(obsRef.current.options.useErrorBoundary, [
120120
currentResult.error,
121121
])
122122
) {

src/reactjs/utils.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
export function shouldThrowError<T extends (...args: any[]) => boolean>(
2-
_useErrorBoundary: boolean | T,
2+
_useErrorBoundary: boolean | T | undefined,
33
params: Parameters<T>
44
): boolean {
55
// Allow useErrorBoundary function to override throwing behavior on a per-error basis
66
if (typeof _useErrorBoundary === 'function') {
77
return _useErrorBoundary(...params)
88
}
99

10-
return _useErrorBoundary
10+
return !!_useErrorBoundary
1111
}

0 commit comments

Comments
 (0)