'React I receive Infinite Loop on Error Boundry / Handling errors
I try to have an Error Boundry for async actions, but then I get an infinite loop. Do you have any ideas about what I'm doing wrong? I tried to add my own hook to catch the errors - and it works but it probably provides an infinite loops unfortunatelly
Code:
import React, { Component } from 'react'
import Dialog from '@mui/material/Dialog'
import DialogActions from '@mui/material/DialogActions'
import DialogContent from '@mui/material/DialogContent'
import DialogContentText from '@mui/material/DialogContentText'
import DialogTitle from '@mui/material/DialogTitle'
import Button from '@mui/material/Button'
export class ErrorHandler extends Component {
state = { error: false }
static getDerivedStateFromError(error) {
return { error }
}
componentDidCatch(error) {
this.setState({ error: true })
}
handleClose = () => {
this.setState({ error: false })
}
render() {
return this.state.error ? (
<div>
{this.props.children}
<Dialog
open={this.state.error}
onClose={this.handleClose}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
>
<DialogTitle id='alert-dialog-title'>{'Error occured'}</DialogTitle>
<DialogContent>
<DialogContentText id='alert-dialog-description'>
Error description
</DialogContentText>
</DialogContent>
<DialogActions>
<Button
onClick={this.handleClose}
autofocus
>
OK
</Button>
</DialogActions>
</Dialog>
</div>
) : (
this.props.children
)
}
}
ErrorHandling:
<ErrorHandler>
<App />
</ErrorHandler>
Custom Hook to catch async errors:
import { useCallback, useState } from 'react'
const useAsyncError = () => {
const [_, setError] = useState()
return useCallback(
(e) => {
setError(() => {
throw e
})
},
[setError]
)
}
export default useAsyncError
Using it:
function Dashboard() {
const [data, setData] = useState([])
const throwError = useAsyncError()
useEffect(() => {
try {
reportService
.getWelcomeReport(request)
.then(
(response) => setData(response.data)
)
.catch((e) => {
throwError(new Error('Asynchronous error'))
})
} catch (e) {
}
}, [])
return (
<div>TEST</div>
)
}
export default Dashboard
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
