Skip to content

componentDidCatch doesn't work in React 16's renderToString #10442

@aickin

Description

@aickin

I tried out a simple test case for the new componentDidCatch error handling code in React 16 SSR with the following code:

import React from "react"
import { renderToString } from "react-dom/server"

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

  componentDidCatch(error, info) {
    // Display fallback UI
    console.log("componentDidCatch");
    this.setState({ hasError: true });
  }

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

class ThrowingComponent extends React.Component {
  render() {
    throw new Error("Ooooops");
  }
}

console.log(renderToString(<ErrorBoundary><ThrowingComponent/></ErrorBoundary>));

and the result with 16.0.0-beta.5 was:

/Users/.../throwingimpl.js:68
      throw new Error("Ooooops");
      ^

Error: Ooooops
    at ThrowingComponent.render (/Users/.../throwingimpl.js:27:11)
    at resolve (/Users/.../node_modules/react-dom/cjs/react-dom-server.node.development.js:1891:18)
    at ReactDOMServerRenderer.render (/Users/.../node_modules/react-dom/cjs/react-dom-server.node.development.js:1988:22)
    at ReactDOMServerRenderer.read (/Users/.../node_modules/react-dom/cjs/react-dom-server.node.development.js:1964:19)
    at renderToString (/Users/.../node_modules/react-dom/cjs/react-dom-server.node.development.js:2234:25)
    at Object.<anonymous> (/Users/.../throwingimpl.js:31:13)
    at Module._compile (module.js:569:30)
    at loader (/Users/.../node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/.../node_modules/babel-register/lib/node.js:154:7)
    at Module.load (module.js:503:32)

As far as I can tell, this code should not throw but should rather output <h1>Something went wrong.</h1>.

I'm afraid that maybe we didn't add componentDidCatch to the new server renderer.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions