Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
Can not update a component while rendering a different component

I am using the useAuth hook to my authContext, so that I can use hook to set global states for my components.

Now, I am trying to navigate to the '/' page if the user was not logged in, and also display a requireLoginAlert to the user in the '/' page after the user was redirected. However, I got the following error when I try to include the setRequireLoginAlert(true) function in requireAuth.js.

Warning: Cannot update a component (`AuthProvider`) while rendering a different component (`RequireAuth`). To locate the bad setState() call inside `RequireAuth`

My requireAuth.js:

const RequireAuth = () => {
  const { auth, setRequireLoginAlert } = useAuth();
  const location = useLocation();

  return (
    auth?.user 
      ? <Outlet />
      : <Navigate to='/' state={{ from: location }} replace />
      && setRequireLoginAlert(true)
  );
};

export default RequireAuth;

My AuthContext.js

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
  const [auth, setAuth] = useState({});
  const [requireLoginAlert, setRequireLoginAlert] = useState(false);

  return (
    <AuthContext.Provider value={{ auth, setAuth, requireLoginAlert, setRequireLoginAlert }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthContext;

I have try using useEffect the display the alert whenever the location has changed, but in this way the alert will keep popping out whenever I go to other pages, which is not ideal. I need a trigger to change the requireLoginAlert state after the user was redirected without error.

Feel free the drop a comment if you have any idea. Thanks a lot.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think you were on the good way with the useEffect approach.

Indeed you have use the location in the dependencies array, but you also need to include a condition based on the current page so that the requireLoginAlert is not called every time

Have you tried something like the following piece of code ?

useEffect(
  () => auth?.user && location === "/" && setRequireLoginAlert(true),
  [auth?.user, location]
);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!