2

Caught the error in my componentDidCatch() method, and the custom error UI is rendered.

What would be a neat way to move on from the error and not make the user to force update the page?

import * as React from "react";

interface ErrorBoundaryState {
    hasError: boolean;
    errorInfo: React.ErrorInfo;
}

export class ErrorBoundary extends React.Component<{}, ErrorBoundaryState> {
    constructor(props: any) {
        super(props);
        this.state = {
            hasError: false,
            errorInfo: undefined,
        };
    }

    public componentDidCatch(error: Error, info: React.ErrorInfo) {
        this.setState({
            hasError: true,
            errorInfo: info
        });
        console.error(error, info);
    }

    public render() {
        if (this.state.hasError) {
            return (
                <h2>Something went wrong, please try again later.</h2>
            );
        }
        return this.props.children;
    }
}

As the hasError set to true, it kind of stays there. Where would be a good place to set it to false and show the children again?

alanmynah
  • 241
  • 2
  • 11

1 Answers1

0

I think that the user wants to know why has been interrupted. So you can display an error saying sorry to the user and saying them that after 5 seconds he can re-use the app.

You can use the setTimeout to set the state to hasError:false after 5 seconds.

Paolo Dell'Aguzzo
  • 1,431
  • 11
  • 14