@xysfe/catch-react-error
v0.0.2
Published
react error boundaries
Downloads
5
Readme
How to use
- install @xysfe/catch-react-error
npm install @xysfe/catch-react-error --save
- Install ES7 Decorator babel plugin
npm install --save-dev @babel/plugin-proposal-decorators
npm install --save-dev @babel/plugin-proposal-class-properties
- babel plugin configuration
{
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }]
]
}
- import @xysfe/catch-react-error
import catchreacterror from "@xysfe/catch-react-error";
- Use @catchreacterror on class component
@catchreacterror()
class Count extends React.Component {
render() {
const { count } = this.props;
if (count === 3) {
throw new Error("count is three");
}
return <h1>{count}</h1>;
}
}
- Use @catchreacterror on functionc component
function Count({ count }) {
if (count === 3) {
throw new Error("count is three");
}
return <h1>{count}</h1>;
}
const SaleCount = catchreacterror()(Count);
- Add a CustomErrorBoundary component
// First, create an normal Error Boundary Component and change it
class CustomErrorBoundary extends React.Component {
constructor (props) {
super (props);
this.state = {hasError: false};
}
static getDerivedStateFromError (error) {
return {hasError: true};
}
componentDidCatch (error, errorInfo) {
//do something as needed
reportToMyLogService (error, errorInfo);
}
render () {
if (this.state.hasError) {
return <h1> Something with my app,fallback ui. </ h1>;
}
}
return this.props.children;
}
}
// Second, pass it as the argument
@catchreacterror(CustomErrorBoundary)
class Count extends React.Component {}
or
const SaleCount = catchreacterror(CustomErrorBoundary)(Count);