I'm practicing typescript and I've run into this bug that won't let me move forward: Property 'isMounted' does not exist on type 'ErrorBoundary'
.
I have the following Boundary component
// React
import React from 'react'
// Librarys
import ReportIcon from '@mui/icons-material/Report';
type ChildrenProp = {
children: React.ReactNode,
}
type BoundaryState = {
error: null|string
}
export default class ErrorBoundary extends React.PureComponent<ChildrenProp, BoundaryState> {
constructor(props:ChildrenProp) {
super(props)
this.isMounted = false
this.state = {
error: null,
}
}
componentDidMount() {
this.isMounted = true
}
componentDidCatch(error) {
this.isMounted && this.setState({ error: error.message })
}
componentWillUnmount() {
this.isMounted = false
}
render() {
if (this.state.error) {
return (
<div className="d-flex h-100 align-items-center justify-content-center flex-column text-muted text-center">
<ReportIcon className="mb-1 fs-4" />
<h4 className="text-secondary">Application Error:</h4>
<code className="col-10 mx-auto">{JSON.stringify(this.state.error)}</code>
</div>
)
}
return this.props.children
}
}
I need to understand why Typescript throws me this error, the this.isMounted
is the cause of this error, but how can I assign a type?. Thanks a lot
CodePudding user response:
Add public isMounted: boolean;
to the component to declare it (the public
is optional)
export default class ErrorBoundary extends React.PureComponent<ChildrenProp, BoundaryState> {
public isMounted: boolean;
constructor(props:ChildrenProp) {
...
}