From fee4a14f180ca4e26c80a735ff7c27b99c1d5174 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sun, 13 Mar 2022 20:22:37 +0100 Subject: [PATCH] fix(mutations): allow passing a function to useErrorBoundary (#3390) --- src/reactjs/tests/useMutation.test.tsx | 51 ++++++++++++++++++++++++++ src/reactjs/useMutation.ts | 2 +- src/reactjs/utils.ts | 4 +- 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/reactjs/tests/useMutation.test.tsx b/src/reactjs/tests/useMutation.test.tsx index 24b9f41c2c..ff5597ba6e 100644 --- a/src/reactjs/tests/useMutation.test.tsx +++ b/src/reactjs/tests/useMutation.test.tsx @@ -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( + () => { + const err = new Error('mock error') + err.stack = '' + return Promise.reject(err) + }, + { + useErrorBoundary: () => { + boundary = !boundary + return !boundary + }, + } + ) + + return ( +
+ + {error && error.message} +
+ ) + } + + const { getByText, queryByText } = renderWithClient( + queryClient, + ( +
+ error boundary +
+ )} + > + +
+ ) + + // 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() diff --git a/src/reactjs/useMutation.ts b/src/reactjs/useMutation.ts index 0427befc69..63a13ef403 100644 --- a/src/reactjs/useMutation.ts +++ b/src/reactjs/useMutation.ts @@ -116,7 +116,7 @@ export function useMutation< if ( currentResult.error && - shouldThrowError(!!obsRef.current.options.useErrorBoundary, [ + shouldThrowError(obsRef.current.options.useErrorBoundary, [ currentResult.error, ]) ) { diff --git a/src/reactjs/utils.ts b/src/reactjs/utils.ts index 4b69f2a972..916982036d 100644 --- a/src/reactjs/utils.ts +++ b/src/reactjs/utils.ts @@ -1,5 +1,5 @@ export function shouldThrowError boolean>( - _useErrorBoundary: boolean | T, + _useErrorBoundary: boolean | T | undefined, params: Parameters ): boolean { // Allow useErrorBoundary function to override throwing behavior on a per-error basis @@ -7,5 +7,5 @@ export function shouldThrowError boolean>( return _useErrorBoundary(...params) } - return _useErrorBoundary + return !!_useErrorBoundary }