Intento tener un límite de error para las acciones asíncronas, pero luego obtengo un bucle infinito. ¿Tienes alguna idea de lo que estoy haciendo mal? Traté de agregar mi propio gancho para detectar los errores, y funciona, pero desafortunadamente probablemente proporcione bucles infinitos.
Código:
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 ) } }Manejo de errores:
<ErrorHandler> <App /> </ErrorHandler>Gancho personalizado para detectar errores asíncronos:
import { useCallback, useState } from 'react' const useAsyncError = () => { const [_, setError] = useState() return useCallback( (e) => { setError(() => { throw e }) }, [setError] ) } export default useAsyncErrorUsándolo:
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