Home > Blockchain >  Can not update a component while rendering a different component
Can not update a component while rendering a different component

Time:05-17

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.

CodePudding user response:

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]
);

  • Related