0

I'm trying to implement generic error page for any unhandled exceptions in React application. However, it seems like the error boundary doesn't work with exceptions thrown by promises such as API operations. I know I could catch the exception at component level and re-throw it at the render method. But this is boilerplate I would like to avoid. How to use error boundary with promises?

I'm using latest React with hooks and react-router for navigation.

1 Answer 1

1

You can do by creating a HOC which will take two parameters First one is the component and second the promise. and it will return the response and loading in the props Please find the code below for your reference.

HOC

import React, { Component } from "react";
function withErrorBoundary(WrappedComponent, Api) {
  return class ErrorBoundary extends Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false, response: null, loading: false };
    }
    async componentDidMount() {
      try {
        this.setState({
          loading: true
        });
        const response = await Api;

        this.setState({
          loading: false,
          response
        });
        console.log("response", response, Api);
      } catch (error) {
        // throw error here
        this.setState({
          loading: 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
    }

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

      return (
        <WrappedComponent
          response={this.state.response}
          loading={this.state.loading}
          {...this.props}
        />
      );
    }
  };
}
export default withErrorBoundary;

How to use HOC

import ReactDOM from "react-dom";
import React, { Component } from "react";
import withErrorBoundary from "./Error";

class Todo extends Component {
  render() {
    console.log("this.props.response", this.props.response);
    console.log("this.props.loading", this.props.loading);
    return <div>hello</div>;
  }
}
const Comp = withErrorBoundary(
  Todo,
  fetch("https://jsonplaceholder.typicode.com/todos/1").then(response =>
    response.json()
  )
);

ReactDOM.render(<Comp />, document.getElementById("root"));

Please check the codesandbox for your refrence

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.