DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on

2 1

Rescript React Error boundary usage

Hi

I was trying to capture the react errors. I had to write the bindings for the ErrorBoundary and its usage is shown below.

The actual ErrorBoundary component is below

// ErrorBoundary.js
import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    //logErrorToMyService(error, errorInfo);
    console.log({ error, errorInfo });
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Enter fullscreen mode Exit fullscreen mode

Bindings to the ErrorBoundary for Rescript.

// ReactErrorBoundary.res
@react.component @module("./ErrorBoundary.js")
external make: (
  ~children: React.element,
  ~onError: ('e, 'i) => unit=?,
  ~renderFallback: ('e, 'i) => React.element=?,
) => React.element = "ErrorBoundary"

Enter fullscreen mode Exit fullscreen mode

Error component to show the react error

// Error.res
module Error = {
  @react.component
  let make = (~error) => {
    <div> {React.string(error)} </div>
  }
}

Enter fullscreen mode Exit fullscreen mode

How to use ReactErrorBoundary in rescript

// ReactErrorBoundary usage
<ReactErrorBoundary fallback={params => <Error 
  error=params.error />}>
  <ComponentThrowingException />
</ReactErrorBoundary>
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay