I am following the tutorial on reactjs.org and I am practicing catching error with Error Boundaries. I have write my own code similar to the tutorial's code but I found that the Boundary does not re-render the fallback UI. I am using version 16.8.6 of React. Here is my code:
ErrorBoundary.js
:
import React from 'react'
export const ErrorContext = React.createContext({
error: null,
errorInfo: null,
clickCount: 0,
increment : () =>{},
})
export default class ErrorBoundary extends React.Component{
constructor(props){
super(props);
this.increment = ()=>{
this.setState(state => ({
clickCount : state.clickCount + 1
}))
}//method to increment clickCount by 1 per click
this.state = {
error: null,
errorInfo: null,
clickCount: 0,
increment: this.increment
}
}
resetDefault(){//method to reset number of click to zero (fix error)
this.setState({
clickCount: 0,
error: null,
errorInfo: null
})
}
componentDidCatch(error,errorInfo){
this.setState({
error: error,
errorInfo: errorInfo
})
console.log(this.state.error)
}
render(){
if(this.state.error){//fallback UI
return(
<div>
<h2>An error has occured!!</h2>
<details>
{this.state.error}
<br/>
{this.state.errorInfo}
</details>
<button onClick = {this.resetDefault.bind(this)}>Click here to fix error </button>
</div>
)
}
return(
<ErrorContext.Provider value = {this.state}>
{this.props.children}
</ErrorContext.Provider>
)
}
}
ErrorThrower
:
import React from 'react'
import {ErrorContext} from './ErrorBoundary'
class ErrorThrower extends React.Component{
static contextType = ErrorContext
constructor(props){
super(props);
}
render(){
if(this.context.clickCount === 6) {
throw new Error('ErrorOccured')
}
return(
<div>
<h2>Number of click count : {this.context.clickCount}</h2>
<button onClick = {this.context.increment}>Click here !!!</button>
</div>
)
}
}
export default ErrorThrower
App.js
:
import React from 'react';
import ErrorBoundary from './components/ErrorBoundary'
import ErrorThrower from './components/ErrorThrower';
function App() {
return (
<div className="App">
<ErrorBoundary>
<ErrorThrower></ErrorThrower>
</ErrorBoundary>
</div>
);
}
export default App;
Following the tutorial (you can find at this link : https://reactjs.org/docs/error-boundaries.html) I have created ErrorThrower
component which render one header and one button. When I click on button more than 5 times, an error will be thrown and React will render the fallback UI to display error log. And I have added another feature that allow me to fix the error (set the click count to 0 ) when I click a button in the fallback UI. However when I run project React does not fallback the UI to display error, it prints out the error stacktrace like normal. In the componentDidCatch()
method the console prints out null value and I think setState()
does not work. Anyone can show me what I did wrong in the code ?