Skip to content

Commit

Permalink
Merge pull request #3689 from preactjs/use-error-boundary-errorinfo
Browse files Browse the repository at this point in the history
Pass `errorInfo` to `useErrorBoundary` calbback
  • Loading branch information
marvinhagemeister committed Aug 21, 2022
2 parents 9457b22 + 61c7eb1 commit 14977dd
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 8 deletions.
4 changes: 2 additions & 2 deletions hooks/src/index.d.ts
@@ -1,4 +1,4 @@
import { PreactContext, Ref as PreactRef } from '../..';
import { ErrorInfo, PreactContext, Ref as PreactRef } from '../..';

type Inputs = ReadonlyArray<unknown>;

Expand Down Expand Up @@ -135,5 +135,5 @@ export function useContext<T>(context: PreactContext<T>): T;
export function useDebugValue<T>(value: T, formatter?: (value: T) => any): void;

export function useErrorBoundary(
callback?: (error: any) => Promise<void> | void
callback?: (error: any, errorInfo: ErrorInfo) => Promise<void> | void
): [any, () => void];
6 changes: 3 additions & 3 deletions hooks/src/index.js
Expand Up @@ -345,16 +345,16 @@ export function useDebugValue(value, formatter) {
}

/**
* @param {(error: any) => void} cb
* @param {(error: any, errorInfo: import('preact').ErrorInfo) => void} cb
*/
export function useErrorBoundary(cb) {
/** @type {import('./internal').ErrorBoundaryHookState} */
const state = getHookState(currentIndex++, 10);
const errState = useState();
state._value = cb;
if (!currentComponent.componentDidCatch) {
currentComponent.componentDidCatch = err => {
if (state._value) state._value(err);
currentComponent.componentDidCatch = (err, errorInfo) => {
if (state._value) state._value(err, errorInfo);
errState[1](err);
};
}
Expand Down
5 changes: 3 additions & 2 deletions hooks/src/internal.d.ts
@@ -1,6 +1,7 @@
import {
Component as PreactComponent,
PreactContext
PreactContext,
ErrorInfo
} from '../../src/internal';
import { Reducer } from '.';

Expand Down Expand Up @@ -75,5 +76,5 @@ export interface ContextHookState {
}

export interface ErrorBoundaryHookState {
_value?: (error: any) => void;
_value?: (error: any, errorInfo: ErrorInfo) => void;
}
20 changes: 19 additions & 1 deletion hooks/test/browser/errorBoundary.test.js
Expand Up @@ -57,7 +57,25 @@ describe('errorBoundary', () => {
rerender();
expect(scratch.innerHTML).to.equal('<p>Error</p>');
expect(spy).to.be.calledOnce;
expect(spy).to.be.calledWith(error);
expect(spy).to.be.calledWith(error, {});
});

it('returns error', () => {
const error = new Error('test');
const Throws = () => {
throw error;
};

let returned;
const App = () => {
const [err] = useErrorBoundary();
returned = err;
return err ? <p>Error</p> : <Throws />;
};

render(<App />, scratch);
rerender();
expect(returned).to.equal(error);
});

it('does not leave a stale closure', () => {
Expand Down

0 comments on commit 14977dd

Please sign in to comment.