Skip to content

Commit

Permalink
fix(mutations): allow passing a function to useErrorBoundary (#3390)
Browse files Browse the repository at this point in the history
  • Loading branch information
TkDodo authored Mar 13, 2022
1 parent bc7263d commit fee4a14
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 3 deletions.
51 changes: 51 additions & 0 deletions src/reactjs/tests/useMutation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,57 @@ describe('useMutation', () => {
})
})

it('should be able to throw an error when useErrorBoundary is a function that returns true', async () => {
let boundary = false
function Page() {
const { mutate, error } = useMutation<string, Error>(
() => {
const err = new Error('mock error')
err.stack = ''
return Promise.reject(err)
},
{
useErrorBoundary: () => {
boundary = !boundary
return !boundary
},
}
)

return (
<div>
<button onClick={() => mutate()}>mutate</button>
{error && error.message}
</div>
)
}

const { getByText, queryByText } = renderWithClient(
queryClient,
<ErrorBoundary
fallbackRender={() => (
<div>
<span>error boundary</span>
</div>
)}
>
<Page />
</ErrorBoundary>
)

// first error goes to component
fireEvent.click(getByText('mutate'))
await waitFor(() => {
expect(queryByText('mock error')).not.toBeNull()
})

// second error goes to boundary
fireEvent.click(getByText('mutate'))
await waitFor(() => {
expect(queryByText('error boundary')).not.toBeNull()
})
})

it('should pass meta to mutation', async () => {
const errorMock = jest.fn()
const successMock = jest.fn()
Expand Down
2 changes: 1 addition & 1 deletion src/reactjs/useMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export function useMutation<

if (
currentResult.error &&
shouldThrowError(!!obsRef.current.options.useErrorBoundary, [
shouldThrowError(obsRef.current.options.useErrorBoundary, [
currentResult.error,
])
) {
Expand Down
4 changes: 2 additions & 2 deletions src/reactjs/utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
export function shouldThrowError<T extends (...args: any[]) => boolean>(
_useErrorBoundary: boolean | T,
_useErrorBoundary: boolean | T | undefined,
params: Parameters<T>
): boolean {
// Allow useErrorBoundary function to override throwing behavior on a per-error basis
if (typeof _useErrorBoundary === 'function') {
return _useErrorBoundary(...params)
}

return _useErrorBoundary
return !!_useErrorBoundary
}

0 comments on commit fee4a14

Please sign in to comment.