score:5
the function passed to useeffect is completing successfully. it defines a function, then successfully calls the function. the effect function returns undefined
normally, so there is nothing for the error boundary to catch.
error boundaries do not catch all possible errors. specifically, from the documentation on error boundaries:
error boundaries do not catch errors for:
- event handlers (learn more)
- asynchronous code (e.g. settimeout or requestanimationframe callbacks)
- server side rendering
- errors thrown in the error boundary itself (rather than its children)
if you want the error boundary to take action, then one option is to save the error in state and rethrow it from the component body. for example:
function mycomponent() {
const [error, seterror] = usestate(null);
if (error) {
throw error;
}
useeffect(() => {
// if loading fails, save the error in state so the component throws when it rerenders
load().catch(err => seterror(err));
}, []);
return <div>...</div>
}
score:0
a class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getderivedstatefromerror() or componentdidcatch(). use static getderivedstatefromerror() to render a fallback ui after an error has been thrown. use componentdidcatch() to log error information.
score:2
problem
basically, you have two things working against you. the first is that the cra has an erroroverlay
which captures errors first and the second is that since event handlers are asynchronous, they don't trigger the componentdidcatch
/getderivedstatefromerror
lifecycles: issue #11409.
the work-around is to capture unhandledrejection
events on the window
.
solution
code
errorboundary.js
import * as react from "react";
const errorboundary = ({ children }) => {
const [error, seterror] = react.usestate("");
const promiserejectionhandler = react.usecallback((event) => {
seterror(event.reason);
}, []);
const reseterror = react.usecallback(() => {
seterror("");
}, []);
react.useeffect(() => {
window.addeventlistener("unhandledrejection", promiserejectionhandler);
return () => {
window.removeeventlistener("unhandledrejection", promiserejectionhandler);
};
/* eslint-disable react-hooks/exhaustive-deps */
}, []);
return error ? (
<react.fragment>
<h1 style={{ color: "red" }}>{error.tostring()}</h1>
<button type="button" onclick={reseterror}>
reset
</button>
</react.fragment>
) : (
children
);
};
export default errorboundary;
hello.js
import react, { useeffect } from "react";
export const hello = () => {
const loader = async () => {
return promise.reject("api error");
};
useeffect(() => {
const load = async () => {
try {
await loader();
} catch (err) {
throw err;
}
};
load();
}, []);
return <h1>hello world!</h1>;
};
index.js
import react from "react";
import { render } from "react-dom";
import { hello } from "./hello";
import errorboundary from "./errorboundary";
const app = () => (
<errorboundary>
<hello />
</errorboundary>
);
render(<app />, document.getelementbyid("root"));
other thoughts
a cleaner approach would be to just display a pop-up/notification about the error instead of overriding the entire ui. a larger and more complex ui means an unnecessarily large ui repaint:
Source: stackoverflow.com
Related Query
- React error boundaries with useEffect and async function, what I'm missing?
- React Error Boundaries not working properly with async function
- How to test useEffect with async function and setState inside
- useEffect cleanup function with Firebase and React
- Trying to integrate jest and react with amchart but getting an error . What could be the issue?
- Handling HTTP error with async await and try and catch clause in react typescript
- React hooks : useMemo and useEffect has a Missing dependency when we are trying to call a function
- Infinite loop error in React JS with useEffect and useState
- React useEffect and useCallback linting error - missing dependency
- Error 400 and 200 with useEffect React Hook
- Setting the initial value of useState with async function using contextAPI and React
- Not sure what to put in callback function for routing with express and react front end
- React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing
- How to call loading function with React useEffect only once
- What is the best way to deal with a fetch error in react redux?
- Getting error after I put Async function in useEffect
- Async validation with Formik, Yup and React
- Error with basic React Example: Uncaught TypeError: undefined is not a function
- How Snapshot testing works and what does toMatchSnapshot( ) function do in Jest Snapshot testing for React components?
- Cannot read property '.then' of undefined when testing async action creators with redux and react
- Syntax error in IE11 with Webpack, Babel and React
- What is the correct order of execution of useEffect in React parent and child components?
- React Error Boundaries not working with React
- Uncaught TypeError: create is not a function using useEffect React Hook with AJAX request
- Is possible to call async function without await keyword? and what happens if we call without await?
- Difference between with and without useEffect in react functional component
- Error using component done with react,redux and react-redux and build with webpack in react application
- React JS : history.push is not a function error and it isn't navigating to a different page onclick of swal
- Mock React useRef or a function inside a functional component with enzyme and jest?
- TypeError: Object(...) is not a function with React Table and moment.js
More Query from same tag
- Map 2 arrays of object to make a loop
- How center the new location of Google Map on React?
- Does react-admin confirmation dialogue accept more than two selection options? I'll like my dialogue box to contan "Yes", "Cancel", "No" options
- Material-UI Grid Overflow Column into next Row
- Render React component with onClick and execute props function
- How can I update the state so that my page gets reloaded automatically and I don't have to reload manually?
- Questions about refs callback in reactjs (ES6 vs non ES6)
- Consuming resources from a React Admin app in another React Admin app
- How to track the firebase login state changes in other component?
- React trigger only one element in array
- Using react-bootstrap-typeahead generating CSS errors
- ReactJS tutorial- Comment form not posting to local server
- Bug getting data from server to client using MERN stack
- React wait variable to load before executing the return
- Adding a string of code to my html by first storing in a variable, then formatting correctly?
- Get user.id as a string from clerk
- How to create a pagination in Redux from an array received by API
- Setting Authorization to specific parts of a component
- Invalid hook call while using no hooks (material-ui v5)
- How to use antd divider to separate two sides of the screen in a react component?
- How to use Google Fonts API in React JS?
- Send props to an array of components
- How to use spread operator on nested javascript objects?
- getting server response with react-dropzone-uploader
- Nextjs - Global.css style not applying/working on pages/components
- How to change state in ReactJS?
- How to pass prop to custom root component in material-ui@next when using TypeScript?
- React custom hook infinite loop
- Responsive Design Problem while using Grid Material UI?
- Proper data format when sending form data from client to server