Skip to content

Instantly share code, notes, and snippets.

@welll
Last active April 1, 2021 00:33
Show Gist options
  • Save welll/390301839bb56b2f1cc65b2aa0d90cd6 to your computer and use it in GitHub Desktop.
Save welll/390301839bb56b2f1cc65b2aa0d90cd6 to your computer and use it in GitHub Desktop.
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
const app = express();
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");
}
}
app.get('/', (req, res) => {
const appString = renderToString(
(
<ErrorBoundary>
<ThrowingComponent />
</ErrorBoundary>
)
);
res.send(appString);
});
const port = 3001;
app.listen(port);
console.log(`Listening on port ${port}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment