Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  150] [ 7]  / answers: 1 / hits: 16108  / 2 Years ago, fri, june 3, 2022, 12:00:00

The changes to strict-mode in React version 18 causes my code to render twice, which causes an error in axios abort controller, but I don't know how to clear the error from the browser console after the app renders twice.


Please note: I am working on a sign-up / log-in app and even after I successfully logged in, React takes me back to the log-in page, because of the axios error


useEffect(() => {
let isMounted = true;
// used by axios to cancel request
const controller = new AbortController();

const getGoals = async () => {
try {
const response = await goalPrivate.get("/goals", {
// option to cancel request
signal: controller.signal
})
console.log(response?.data);
// set goals state when component mounts
isMounted && setGoals(response?.data);
} catch (error) {
console.log(error.message);
// when refreshToken expires
navigate("/login", { state: { from: location }, replace: true });
}
}

getGoals();

// cleanup function
return () => {
// don't set state if component unmounts
isMounted = false;
// cancel request if component unmounts
controller.abort();
}

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])



shows


More From » reactjs

 Answers
38

React 18 now has Strict.Mode which can mount, unmount, and remount components which causes the abortController to issue an error on the first unmount. Remember, this only happens in development mode when Strict.Mode is applied in your index.js. We can check for that behaviour while in development-mode.


try {
// fetch API data
} catch (error) {
if (process.env.NODE_ENV === "development" && error) {
// ignore the error
console.log(error.message);
} else {
// when refreshToken expires, go back to login
navigate("/login", { state: { from: location }, replace: true });
}
}

[#50030] Sunday, March 13, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabrina

Total Points: 92
Total Questions: 92
Total Answers: 85

Location: Palestine
Member since Thu, Feb 2, 2023
1 Year ago
;