Giter VIP home page Giter VIP logo

react-error-boundary's Introduction

react-error-boundary

Reusable React error boundary component. Supports all React renderers (including React DOM and React Native).

If you like this project, ๐ŸŽ‰ become a sponsor or โ˜• buy me a coffee

Getting started

# npm
npm install react-error-boundary

# pnpm
pnpm add react-error-boundary

# yarn
yarn add react-error-boundary

API

ErrorBoundary component

Wrap an ErrorBoundary component around other React components to "catch" errors and render a fallback UI. The component supports several ways to render a fallback (as shown below).

Note ErrorBoundary is a client component. You can only pass props to it that are serializeable or use it in files that have a "use client"; directive.

ErrorBoundary with fallback prop

The simplest way to render a default "something went wrong" type of error message.

"use client";

import { ErrorBoundary } from "react-error-boundary";

<ErrorBoundary fallback={<div>Something went wrong</div>}>
  <ExampleApplication />
</ErrorBoundary>

ErrorBoundary with fallbackRender prop

"Render prop" function responsible for returning a fallback UI based on a thrown value.

"use client";

import { ErrorBoundary } from "react-error-boundary";

function fallbackRender({ error, resetErrorBoundary }) {
  // Call resetErrorBoundary() to reset the error boundary and retry the render.

  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
    </div>
  );
}

<ErrorBoundary
  fallbackRender={fallbackRender}
  onReset={(details) => {
    // Reset the state of your app so the error doesn't happen again
  }}
>
  <ExampleApplication />
</ErrorBoundary>;

ErrorBoundary with FallbackComponent prop

React component responsible for returning a fallback UI based on a thrown value.

"use client";

import { ErrorBoundary } from "react-error-boundary";

function Fallback({ error, resetErrorBoundary }) {
  // Call resetErrorBoundary() to reset the error boundary and retry the render.

  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
    </div>
  );
}

<ErrorBoundary
  FallbackComponent={Fallback}
  onReset={(details) => {
    // Reset the state of your app so the error doesn't happen again
  }}
>
  <ExampleApplication />
</ErrorBoundary>;

Logging errors with onError

"use client";

import { ErrorBoundary } from "react-error-boundary";

const logError = (error: Error, info: { componentStack: string }) => {
  // Do something with the error, e.g. log to an external API
};

const ui = (
  <ErrorBoundary FallbackComponent={ErrorFallback} onError={logError}>
    <ExampleApplication />
  </ErrorBoundary>
);

useErrorBoundary hook

Convenience hook for imperatively showing or dismissing error boundaries.

Show the nearest error boundary from an event handler

React only handles errors thrown during render or during component lifecycle methods (e.g. effects and did-mount/did-update). Errors thrown in event handlers, or after async code has run, will not be caught.

This hook can be used to pass those errors to the nearest error boundary:

"use client";

import { useErrorBoundary } from "react-error-boundary";

function Example() {
  const { showBoundary } = useErrorBoundary();

  useEffect(() => {
    fetchGreeting(name).then(
      response => {
        // Set data in state and re-render
      },
      error => {
        // Show error boundary
        showBoundary(error);
      }
    );
  });

  // Render ...
}

Dismiss the nearest error boundary

A fallback component can use this hook to request the nearest error boundary retry the render that originally failed.

"use client";

import { useErrorBoundary } from "react-error-boundary";

function ErrorFallback({ error }) {
  const { resetBoundary } = useErrorBoundary();

  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
      <button onClick={resetBoundary}>Try again</button>
    </div>
  );
}

withErrorBoundary HOC

This package can also be used as a higher-order component that accepts all of the same props as above:

"use client";

import {withErrorBoundary} from 'react-error-boundary'

const ComponentWithErrorBoundary = withErrorBoundary(ExampleComponent, {
  fallback: <div>Something went wrong</div>,
  onError(error, info) {
    // Do something with the error
    // E.g. log to an error logging client here
  },
})

// Can be rendered as <ComponentWithErrorBoundary {...props} />

FAQ

ErrorBoundary cannot be used as a JSX component

This error can be caused by a version mismatch between react and @types/react. To fix this, ensure that both match exactly, e.g.:

If using NPM:

{
  ...
  "overrides": {
    "@types/react": "17.0.60"
  },
  ...
}

If using Yarn:

{
  ...
  "resolutions": {
    "@types/react": "17.0.60"
  },
  ...
}

This blog post shows more examples of how this package can be used, although it was written for the version 3 API.

react-error-boundary's People

Contributors

50bbx avatar andarist avatar armand1m avatar bespokebob avatar brizer avatar bvaughn avatar doomsower avatar erasmus001 avatar formatlos avatar hally9k avatar hanse avatar imp-dance avatar joealden avatar kentcdodds avatar kubajastrz avatar manudeli avatar marcosvega91 avatar mayank23 avatar me4502 avatar michaeldeboey avatar mmiller42 avatar mrgaogang avatar sapegin avatar smurf667 avatar tommarien avatar vladkens avatar voxtex avatar vsravan707 avatar wild-lotus avatar wrathofzombies avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-error-boundary's Issues

UMD version can be inadvertently tree-shaken out because `sideEffects` is set to false

What you did:

Attempt to bundle react-error-boundary using Rollup.js with nodeResolve({browser: true}).

What happened:

The UMD version of react-error-boundary is used and its content are completely gone in the bundled version.

Reproduction repository:

https://replit.com/@hongrich/react-error-boundary

Problem description:

react-error-boundary includes a UMD version as the browser entry point in package.json and it also specifies "sideEffects": false. These two options configured in this way are not compatible.

This reproduction shows the problem this can cause by bundling using Rollup.js. Using the node-resolve and commonjs plugin, we also set browser: true so it'd pick the browser entry point from package.json which is the UMD version.

Press the "run" button to run Rollup.
Note that react-error-boundary.umd-<hash>.js exports just {exports: {}}
and this is used in b-<hash>.js as part of the Bar function.

//โ†’ react-error-boundary.umd-b07bb2f5.js:
var reactErrorBoundary_umd = {exports: {}};

export { reactErrorBoundary_umd as r };

//โ†’ b-8274de67.js:
import { r as reactErrorBoundary_umd } from './react-error-boundary.umd-b07bb2f5.js';

const Bar = () => {
  return reactErrorBoundary_umd.exports.ErrorBoundary
};

export { Bar };

Suggested solution:

Either removing "sideEffects": false from package.json or changing the browser field so that it doesn't export the UMD version are both reasonable solutions.

For reference, here are some other libraries built with kcd-scripts and none of them have this particular combination of fields (most just export CJS in main and ESM in module): https://sourcegraph.com/search?q=context:global+kcd-scripts+build+--bundle+repo:npm/&patternType=literal

Types for ErrorBoundary?

  • react-error-boundary version: 2.3.1
  • node version:14.4
  • npm version: 6.4.7

Relevant code or config

            <ErrorBoundary FallbackComponent={errorFallback}>
            </ErrorBoundary>

What you did: Wrapped a section of JSX with the ErrorBoundary component

What happened:

Visual Studio Code complains with a red squiglly line that "no overload matches this call"

Problem description:

I am thinking that the reason that the JSX for ErrorBoundary is causing a warning is that this is inside of a .tsx component and I need type information for the props for ErrorBoundary.

Suggested solution:

Documentation on how to use ErrorBoundary in a TypeScript component.

image

Types not being included in the build

Hello!

First, thanks for the new version @kentcdodds :)

Not sure if i'm meant to be doing anything differently but after installing the latest versions v2.x, the types are not being included. So the TS compiler + VSCode are not happy.

Does the index.d.ts not needed to be included in the files key in package.json?

I'm not 100% sure of these things as im new to TS, so don't know how to help too much.

Thanks

FallbackComponent not rendering

Relevant code:

function ErrorFallback({ error }) {
		return (
			<div role="alert">
				<p>Something went wrong:</p>
				<pre style={{ color: "red" }}>{error.message}</pre>
			</div>
		);
	}

	return (
			<ErrorBoundary
				FallbackComponent={ErrorFallback}
				onReset={() => window.sessionStorage.clear()}
				onError={(error) => {
					console.log(error);
				}}
			>
                            <button onClick={( ) => {throw new Error("Testing with an error")}}>Error thrower</button>
                       </ErrorBoundary>

When I click on the button that triggers an error the FallbackComponent doesn't render, even though the error gets logged(onError recognises it). Am I missing something?

Unnecessary dependencies on package.json when installing

Even thought most of these dependencies were on my devDependencies, yarn add it to yarn.lock and node_modules:

"dependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-runtime": "^6.23.0",
    "prop-types": "^15.5.10",
    "webpack": "^3.3.0"
  },

I believe most of those dependencies should be a devDependency and prop-types is not a dependency, since you use flow

Don't assume all errors are `Error`

Getting this with MobX

checkPropTypes.js:20 Warning: Failed prop type: Invalid prop `error` of type `String` supplied to `ErrorBoundaryFallbackComponent`, expected instance of `Error`.
    in ErrorBoundaryFallbackComponent (created by ErrorBoundary)

Since you can throw any object, an error boundary shouldn't expect only Error instances.

How to reset error on mount component?

Hi,

  • react-error-boundary version: 3.1.1
  • node version: 14

What you did:
I'm using react-error-boundary with suspense mode.
I don't know how to reset error on mount?

What happened:

  • Page_1: Implement ErrorBoundary and Susspense => throw error => <FallbackComponent />
  • Go to Page_2: The Page_1 will be unmount.
  • Back again to Page_1: The Page_1 will be mount. But why <FallbackComponent /> is still.

Reproduction:
https://codesandbox.io/s/busy-http-53kvh?file=/src/App.tsx

Steps:

  1. Click Toggle Data button: After 3s the <FallbackComponent /> will appear.
  2. Click Toggle Data button: The <YourData /> will be unmounted.
  3. Click Toggle Data button: The error should be reset.

React Router stopped working after Error Boundary and history.push doesn't work. How can it be fixed?

  • react-error-boundary version: 3.1.3
  • node version: 14.17.1
  • npm version: 6.14.13

Relevant code or config

<Router>
  <ErrorBoundary>
    ...
  </ErrorBoundary>
</Router>

history.push('...') - doesn't work in the FallbackComponent

What you did:
Added new Exception to test Error Boundary
What happened:
App crashed, I can see my FallbackComponent

Reproduction repository:

Problem description:
history.push doesn't work from within ErrorBoundary component
Suggested solution:

Bug: onResetKeys only triggers reset after second render

  • react-error-boundary version: 3.0.2
  • node version:14
  • npm version:6.14

Relevant code or config
It seems to occur because of the return statement here:

if (error !== null && !this.updatedWithError) {
this.updatedWithError = true
return
}

What you did:

export const ErrorBoundary = ({ children }) => {
  const location = useLocation();
  return (
    <ReactErrorBoundary
      FallbackComponent={FallbackComponent}
      resetKeys={[location]}
    >
      {children}
    </ReactErrorBoundary>
  );
};

What happened:
I have to click the "no error" link twice before the error boundary resets.
This only occurs the first time when I load the page. After that there is issue.

Here you can see I have to click twice on "no error" after the refresh. The url changes on the first click, the errorboundary resets on the 2nd click.
errorboundary-bug-2020-10-19_13 46 27

Reproduction repository:
https://github.com/0xR/errorboundary

For some reason there is no issue on codesandbox:
https://codesandbox.io/s/hungry-mountain-lvggg?file=/src/App.js

Problem description:

Suggested solution:
Remove the return statement:

ErrorFallback rendered for a brief moment then the default dev error page displays

  • react-error-boundary version: 3.1.3
  • node version: 14.17.0
  • npm version: 7.15.1

Relevant code or config

// Used the code from your blog but wrapping my own App
function App() {
  return (
    <>
      <ErrorBoundary FallbackComponent={ErrorFallback}>
        <LoginPage/>
      </ErrorBoundary>
    </>
  )
}

const LoginPage = () => {


  const Bomb = () => {
      throw new Error('๐Ÿ’ฅ CABOOM ๐Ÿ’ฅ');
  };

const LoginPage = () => {
  // relevant code - Hold ctrl and click the Logout button to go ๐Ÿ’ฅ
  <button
      className="neu-button"
      onClick={(e) => {
          e.persist();
          if (e.ctrlKey) {
              console.log('Testing Diagnostics');
              setErrorDetails(new Error('Testing error handler'));
          } else {
              signOff();
          }
      }}
  >
      Logout {errorDetails ? <Bomb /> : null}
  </button>

What you did:
Used the code from the blog and README.md to display an ErrorFallback render instead of the default dev page error vomit.

What happened:
The ErrorFallback component is rendered for a brief moment, but then the default dev page is displayed (see screen shot)

image

Problem description:
ErrorFallback rendered for a brief moment then the default dev error page displays

Suggested solution:
Prevent dev page render when using react-error-bound (I'm not sure this is even possible.) Maybe this is a flag I can set in Chrome(?)

I've not tried a production build yet (I just started experimenting with error-boundary to see if it's a good fit for my project). So this may just be a minor nuisance of a problem. If so please comment and close.

Usage with next.js?

How can I integrate with Next.js? I tried testing locally by triggering an error, but Next.js own error handler takes precedence.

Provide extra props to fallback component

I would like to pass extra props into the fallback component.

My use case:

const _Uploader = lazy(() => import('uploader'));

type Props = { onRequestClose: () => void };
const Uploader: SFC<Props> = props => (
  <ErrorBoundary FallbackComponent={MyErrorComponent}>
    <Suspense fallback={<MyLoadingComponent {...props} />}>
      <_Uploader {...props} />
    </Suspense>
  </ErrorBoundary>
);

I want my fallback component, MyErrorComponent, to receive the prop onRequestClose, in the same way I provide it to MyLoadingComponent.

Perhaps the fallback component should be provided as a render prop instead of as a Component?

props => <ErrorBoundary fallback={
  ({ error }) => <MyErrorComponent error={error} {...props} />
} />

Feature Request: Provide a way to clear the error

What?

Would you provide a way to clear the error in ErrorBoundary component to clear the FallbackComponent ?

Suggestion

If error state can be set via prop, one should be able to clear it depending on outter component's state.
Right now, there is no way to get around the ErrorBoundary without the following workaround

Workaround

A workaround I used is to create a ref assigned to the ErrorBoundary and cleared in onStepClick.

class Wizard extends Component {
  errorBoundary = React.createRef();

  // redacted unrelevant code...
  
  onStepClick = current => {
    this.errorBoundary.current.state.error = null;
  };

  
  render() {
    const { current } = this.state;

    return (
      <div>
        <Steps current={current}>
          {steps.map((item, step) => (
            <Steps.Step
              key={item.title}
              onClick={e => this.onStepClick(step)}
            />
          ))}
        </Steps>
        <div className="steps-content">
          <ErrorBoundary
            ref={this.errorBoundary}
            FallbackComponent={ErrorFallbackComponent}
          >
            {this.getContent()}
          </ErrorBoundary>
        </div>
      </div>
    );
  }
}

Demos

I've created a SandBox demo for the demonstration.

Edit demo-cant-clear-react-error-boundary-error

& Here is the link to the video of how the demo works.

Update state with getDerivedStateFromError rather than componentDidCatch

The componentDidCatch lifecycle method exists for side effects (e.g. logging). Using componentDidCatch to update state and re-render after an error is an anti-pattern and future versions of React will likely skip over error boundaries that don't define getDerivedStateFromError.

When "error boundaries" were first introduced in v16.0, componentDidCatch was the only API available. The static getDerivedStateFromError API was added in v16.6 to improve the error handling process to avoid the necessity to render an intermediate, broken state before calling the commit-phase componentDidCatch hook and rendering again to show fallback UI.

I don't use this package for anything so I had forgotten about it being outdated until this morning.

Note that this would technically be a breaking change since it would raise the minimum version of React supported from 16.0 to 16.6. Looks like @kentcdodds already raised the "react" dependency to 16.13+ via #46 ๐Ÿ˜… Guess this wouldn't be a breaking change after all then.

'ErrorBoundary' cannot be used as a JSX component

Hi guys, I get a strange typescript error when I use the default first example from your lib:

'ErrorBoundary' cannot be used as a JSX component, any chance you had seen that before?

Screenshot 2022-04-15 at 15 41 08

  • react-error-boundary version: 3.1.4
  • node version: 14.19.0
  • npm version: 6.14.16

`
import {ErrorBoundary} from 'react-error-boundary'
function ErrorFallback({error, resetErrorBoundary}) {
return (


Something went wrong:


{error.message}

Try again

)
}
const ui = (
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => {
// reset the state of your app so the error doesn't happen again
}}

<ComponentThatMayError />
) `

Production build

In production build how i will log in which file/component i got the error?

Error type is unknown, not `Error`?

In the types, the error is typed as Error. However, in JS any type can be thrown, e.g. throw "foo";.

Should we correct the type of the error to unknown (in TypeScript terms), or is there something that converts it to an Error?

Remove ErrorBoundary on path change

  • react-error-boundary version: 3.1.3
  • node version: 12.16.2
  • npm version: 6.14.4

Relevant code or config

export default function PrivateRoute({ component: Component, path, ...rest }) {
    const { data } = useSelector((state) => state.userInfo);
    return (
        <Route {...rest} path={path}
            render={(props) => {
                return <ErrorBoundary FallbackComponent={ErrorFallback}><Component {...props} {...data} /></ErrorBoundary>
            }}
        />
    )

}

What you did:
I have bind ErrorBoundary in Route render in PrivateRoute function as I want my all PrivateRouteComponents to be covered with ErrorBoundary

What happened:
It's working fine when any error comes, FallbackComponent gets render, but now when I change the path/route, I don't want FallBackComponet to render again as I have changed my Path and updated path UI should render now.

Reproduction repository:

Problem description:

Suggested solution:

As (and recommend) fallback prop

Considering this is similar in spirit to Suspense, it would be nice if they share a similar more obvious API.

I really liked this code sample from Joe Savona's talk at react conf:

IMG_20191025_094055

Thoughts?

typescript error : Parameter 'props' implicitly has an 'any' type.

src/base/error-boundary/ErrorBoundary.tsx(4,15):
Parameter 'props' implicitly has an 'any' type. TS7006

2 | 
3 | class ErrorBoundary extends React.Component {

4 | constructor(props) {
| ^
5 | super(props);
6 | this.state = { hasError: false };
7 | }

this is my code const container = document.getElementById('root')

function ErrorFallback({error, resetErrorBoundary}: FallbackProps) {
return (


Something went wrong:


{error.message}

Try again

)
}

ReactDOM.render(
<React.StrictMode>
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() =>console.log("on Reset error boundaries")}
// resetKeys={[false]}
>


</React.StrictMode>,
container
);

help... is this is a bug or user issue :(
If it is my mistake then how to use it right?

Re-render ErrorFallback from onError handler output

  • react-error-boundary version: 3.0.2
  • node version: 12.19.0
  • npm version: 6.14.8

This is not a failure but instead a question about a possible use case.

<ErrorBoundary
    FallbackComponent={ErrorFallback}
    onError={defaultErrorHandler}
  >
    <Content store={store} />
  </ErrorBoundary>,
  1. I have a set an ErrorBoundary at the root of the application.
  2. Once the boundary catches the error, I will render the fallback and trigger onError to log information to the server.
  3. In onError handler among the error itself, I also want to send something else, for instance the exact timestamp of the error.
  4. I want to render this same timestamp value in Fallback, so the user is also able to look at the error and report it manually with the same exact information: error and timestamp.
  5. If I use it as below I don't have a connection between onError handler and ErrorFallback component.

Is there a way to do this with current implementation?

Suggested solution:

  1. Re-render ErrorFallback once with returned output of onError handler:

Something like:

const defaultErrorHandler = ({ error }) => {
     const {date} = logTheError(error);
     return { date };
}
function ErrorFallback({error, resetErrorBoundary, onErrorProps}) {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre>{error.message}</pre>
      {onErrorProps && <pre>{onErrorProps.date}</pre>}
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  )
}

Thanks!

Keep rendering children on error

As always, thank you for this module!

I was wondering if there is a way to catch errors but keep rendering the childrens. For instance, I would like to catch errors and show a toast alert over the content, but keeping it instead of replacing it with the fallback component. Is this possible?

Thanks!

Difference between FallbackComponent, fallbackRender and fallback

What is the exact difference between all of those props?

I think fallback could receive the error and resetErrorBoundary function as fallbackRender, and the same for FallbackComponent, is there a reason to use FallbackComponentwhenfallbackRenderdoes the same? Or usefallbackRenderwhen I could inline the definition ofFallbackComponent` to reset the parent component state?

I'm sure there is a reasoning behind all of those different props but I'm not sure at a first glance ๐Ÿค”

Replace FallbackComponent with fallback

I think it would be nice if the <ErrorBoundary> would have a similar API as <Suspense> (fallback instead of FallbackComponent). Don't know if this have been discussed before though.

function App() {
  return <ErrorBoundary fallback={<MyCustomFallback />} />
}

I can create a PR if this is something you'd want to add. Can be a non-breaking change if we keep the FallbackComponent prop.

Expose a decorator function for Redux containers.

I propose exposing an additional function that returns the given component wrapped with the error boundary component. Much like connect() from the react-redux api.

When exposing the class alone, it lends it's self to wrapping a component in JSX which isn't a good fit in some scenarios. For example if a Redux container is referenced in a React Router route as a component reference there is no nice place to use this lib.

With a function as described we could do the following in our redux continers:

export default connect(mapStateToProps, mapDispatchToProps)(
   withErrorBoundary(Component, FallbackComponent, errorHandler)
)

Cannot wrap FallbackComponent with styled components

  • react-error-boundary version: 2.3.0
  • node version: 12.16.1
  • npm version: 6.13.4

Relevant code or config

const ErrorFallbackTop: React.FC<ErrorFallbackProps> = ({
  error: { message },
  className,
}): JSX.Element => {
  return (
    <div className={className}>
      <div>{message}</div>
    </div>
  );
};

export default styled(ErrorFallbackTop)`
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
`;

What you did: wrapped FallbackComponent in styled-components styled() method.

What happened:

react-error-boundary.umd.js?e895:109 Uncaught (in promise) Error: react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop
    at ErrorBoundary.render (react-error-boundary.umd.js?e895:109)
    at finishClassComponent (react-dom.development.js?61bb:17160)
    at updateClassComponent (react-dom.development.js?61bb:17110)
    at beginWork (react-dom.development.js?61bb:18620)
    at HTMLUnknownElement.callCallback (react-dom.development.js?61bb:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js?61bb:237)
    at invokeGuardedCallback (react-dom.development.js?61bb:292)
    at beginWork$1 (react-dom.development.js?61bb:23203)
    at performUnitOfWork (react-dom.development.js?61bb:22154)
    at workLoopSync (react-dom.development.js?61bb:22130)

No only Error for FallbackProps

I'm using React-query, and we can type our error. But there is a conflit with react-error-boundary since the type is not an Error type, but a custom. How can we deal with that ?

image

  • react-error-boundary version: 3.1.0
  • node version: 12.19.1
  • npm version: 6.14.10

Relevant code or config

const OrderDetailsViews = (
  props: RouteComponentProps<TParams>
): React.ReactElement => {
  const { match } = props
  const { t } = useTranslation()
  const orderId = Number(match.params.id)
  const handleError = useErrorHandler()

  const { data: order, error, refetch: refetchOrders } = useQuery<
    FindOneOrder,
    ApiError
  >(['order-details', orderId], () => api.orders.findOneComplete(orderId), {
    onError: err => handleError(err) <-- ERROR TYPE
  })
}

Suggested solution: We can pass our type like : handleError<ApiError>(err)

OR

interface FallbackProps<T extends Error> { <-- We can pass something else
    error: T;
    resetErrorBoundary: (...args: Array<unknown>) => void;
}

License?

Hello, I cannot find a LICENSE file in the repository. npm says this has MIT license. Could you explicitly add a LICENSE file? Thanks!

1.2.4 missing dist?

I just had a build upgrade to 1.2.4, and it appears there is no dist directory, so the main in package.json fails to resolve.

Reverting back to 1.2.3 seems to fix the problem.

How can i use componentStack in FallbackComponent?

Problem description:
I need to use componentStack in FallbackComponent but i see that the FallbackComponent only takes error and resetErrorBoundary parameters. That's why I can't access the componentStack information. How can I do it?

Build Error - Declaration or statement expected. TS1128

Hi, I've ran into bugs whilst trying to create a production build of my application the error seems to be related with TS1128 Declaration or Statement Expected.

Creating an optimized production build...
Failed to compile.

/home/runner/work/.../node_modules/react-error-boundary/dist/index.d.ts
TypeScript error in /home/runner/work/.../node_modules/react-error-boundary/dist/index.d.ts(53,1):
Declaration or statement expected.  TS1128

    51 | declare function useErrorHandler<P = Error>(givenError?: P | null | undefined): React.Dispatch<React.SetStateAction<P | null>>;
    52 | export { ErrorBoundary, withErrorBoundary, useErrorHandler };
  > 53 | export type { FallbackProps, ErrorBoundaryPropsWithComponent, ErrorBoundaryPropsWithRender, ErrorBoundaryPropsWithFallback, ErrorBoundaryProps, };
       | ^
    54 |


npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ... build: `react-scripts build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the ... build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/runner/.npm/_logs/2020-12-02T17_39_28_869Z-debug.log
Error: Process completed with exit code 1.

"react-error-boundary": "^3.1.0",

This is executing via GitHub actions to app-engine, so I'd assume it's using the latest version of NPM / Node.

Errors do not get catched

  • react-error-boundary version: 3.1.4
  • node version: codesandbox
  • npm version: codesandbox

Relevant code or config

function TestError() {
  function onClick() {
    throw Error("ASD");
  }

  return <button onClick={onClick}>toggle error</button>;
}

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <ErrorBoundary fallback={<h2>Error occured</h2>}>
        <TestError />
      </ErrorBoundary>
    </div>
  );
}

What you did:
I was trying out the library but I cant understand why the previous error does not get catched. Am I missing something?
What happened:
Error gets thrown normally and I get the normal dev error screen.
image

Reproduction repository:
https://codesandbox.io/s/errorboundary-test-qidf1?file=/src/App.tsx:77-433

Problem description: /

Suggested solution: /

First `resetKeys` update ignored when error triggered on mount

  • react-error-boundary version: 3.1.0
  • node version: 12.16.1
  • yarn version: 1.22.5

What you did:

I use ErrorBoundary with resetKeys, with the error being triggered on ErrorBoundarymount. Then I trigger a reset via resetKeys

What happened:

The ErrorBoundary error state is not reset until the second resetKeys update.

Reproduction repository:

https://codesandbox.io/s/react-error-boundaryignored-update-issue-fcfyi?file=/src/App.js
This is the same code as in Error Recovery example, but with explode state initialized as true.
Try clicking "toggle explode" button right after the initial render: it does not get reset.

Problem description:

this.updatedWithError flag is not set on component mount, only on component update, so if the error is triggered on component mount, 2 extra updates are needed instead of one. The first one sets the this.updatedWithError and the second ones resets the state.

Suggested solution:

Adding:

  componentDidMount() {
    const {error} = this.state
    if (error !== null) {
      this.updatedWithError = true
    }
  }

Allow rendering of children components

  • react-error-boundary version: 3.1.4
  • node version: 14.18.1
  • npm version: 6.14.15

Relevant code or config

      const props = {
        error,
        resetErrorBoundary: this.resetErrorBoundary,
      }

Problem description:

I want to continue showing the children components after the error has been caught, so ErrorBoundary acts like a transparent container.

Suggested solution:

Allow rendering of child components inside fallback components by passing children in props on line https://github.com/bvaughn/react-error-boundary/blob/master/src/index.tsx#L121-L124.

_the simplest way_ example not compiling in typescript

  • react-error-boundary version: 2.2.2
  • node version: 12.16.1
  • yarn version: 1.22.4
  • typescript version: 3.9.2

What you did

Trying to compile the simplest way example from Usage in docs with typescript.
https://github.com/bvaughn/react-error-boundary#usage

(Since the onError example has type annotations and type definitions are shipped, I'm assuming typescript is supported for this project.)

What happened:

Compile error

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<ErrorBoundaryPropsWithFallback> | Readonly<ErrorBoundaryPropsWithComponent> | Readonly<...>): ErrorBoundary', gave the following error.
    Type '({ error, componentStack, resetErrorBoundary }: { error: any; componentStack: any; resetErrorBoundary: any; }) => Element' is not assignable to type 'ComponentType<FallbackProps>'.
      Type '({ error, componentStack, resetErrorBoundary }: { error: any; componentStack: any; resetErrorBoundary: any; }) => Element' is not assignable to type 'FunctionComponent<FallbackProps>'.
        Types of parameters '__0' and 'props' are incompatible.
          Type 'PropsWithChildren<FallbackProps>' is not assignable to type '{ error: any; componentStack: any; resetErrorBoundary: any; }'.
            Property 'error' is optional in type 'PropsWithChildren<FallbackProps>' but required in type '{ error: any; componentStack: any; resetErrorBoundary: any; }'.
  Overload 2 of 2, '(props: ErrorBoundaryProps, context?: any): ErrorBoundary', gave the following error.
    Type '({ error, componentStack, resetErrorBoundary }: { error: any; componentStack: any; resetErrorBoundary: any; }) => Element' is not assignable to type 'ComponentType<FallbackProps>'.
      Type '({ error, componentStack, resetErrorBoundary }: { error: any; componentStack: any; resetErrorBoundary: any; }) => Element' is not assignable to type 'FunctionComponent<FallbackProps>'.

Reproduction:

import React from 'react';
import { ErrorBoundary } from 'react-error-boundary';

function ErrorFallback({ error, componentStack, resetErrorBoundary }) {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre>{error.message}</pre>
      <pre>{componentStack}</pre>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
}

const ComponentThatMayError = () => <div />;

const ui = (
  <ErrorBoundary
    FallbackComponent={ErrorFallback}   <-- compile error is here
    onReset={() => {
      // reset the state of your app so the error doesn't happen again
    }}
  >
    <ComponentThatMayError />
  </ErrorBoundary>
);

Suggested solution:

Update the docs with a working example.

Show some Fallback component

Hi, thanks for this lib ;)

Is there a way to show the fallback component replacing the component that throws the error?

I don't want to put <ErrorBoundary><Products /> <ErrorBoundary>, <ErrorBoundary><People /> <ErrorBoundary>, <ErrorBoundary><User /> <ErrorBoundary> inside of each component that expects data from API.

I just want to put and then it will show some component fallback when crashing the Products component.

PNPM - Receiving a react error that prop-types could not be found

When using the PNPM package manager, any dependecies not explicitly mentioned in the package.json will be ignored at time of package installation.

The following code (found in ErrorBoundaryFallbackComponent.js) make the following reference to the prop-types package.

ErrorBoundaryFallbackComponent.propTypes = {
  componentStack: require("prop-types").string.isRequired, <---
  ...
}

React apps throw the error Cannot find module: 'prop-types'. Make sure this package is installed. because the package was never installed due to no mention of it in the package.json

The fix, is to add prop-types as a dependency or mark as a peerDependency in the package.json.

Not Working with Childrens

I may be using it wrong, but here it goes.

  • react-error-boundary version: ^3.1.3
  • node version: v14.17.0
  • npm version: 7.14.0

Relevant code or config

image

What you did:

  • Created a <Page />.
  • Inside this <Page />, wrapped its childrens with react-error-boundary.
  • Created a <Home /> which uses this <Page /> with a button which once clicked throw new Error().

What happened:

  • Once clicked into this button, the error popups but the FallbackComponent (Error) is not shown

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.