Home > database >  Why is useEffect() not working in my code
Why is useEffect() not working in my code

Time:01-31

const [open, setOpen] = useState(false);


useEffect(() => {
    if(!token){
        return <Navigate to="/auth/login"/>
    }
    getMe(token)
}, [token, getMe])

return (
    <RootStyle>
        <DashboardNavbar onOpenSidebar={() => setOpen(true)} />
        <DashboardSidebar isOpenSidebar={open} onCloseSidebar={() => setOpen(false)} />
        <MainStyle>
            <Outlet />
        </MainStyle>
    </RootStyle>
);

}

const mapStateToProps = ({ auth }) => ({
    token: auth.token ? auth.token.token : null
})

const mapDispatchToProps = (dispatch) => ({
    getMe: (token) => dispatch(fetchMe(token)),
})

The code above is trying to check if there is token, if not user is redirected to login page else a function that calls the user object from database runs. The token is a destructured prop.

But the problem is the entire block seems not to be noticed by browser for some reason. When i move the getMe() function outside useEffect is works. debugger isn't even noticed! what could be the problem here?

Running the code below without useEffect will work. But there might be lots of re-renders which might lead to a bug.

if(!token){
    return <Navigate to="/auth/login"/>
}
getMe(token)

That is why i am wraping all of the above code to useEffect() in such a way that only when the component mounts and if token changes the function getMe() should run.

useEffect is not working at all. even if i just put a console statement

CodePudding user response:

Are you sure that your token has a value and that it really changes to trigger the useEffect? Do a simple console.log of the token at the top of the useEffect.

What is the result of the useEffect right now? Does it navigate to '/auth/login' as if the token was empty? Also, you could post more of your code to let us see the destructuring of your props.

CodePudding user response:

You don't need a return for useEffect, just <Navigate to="/auth/login"/> should work

CodePudding user response:

You can do a empty return in your useEffect. And when returning the components to render check if the token is set, if not return the Navigate component

useEffect(() => {
  if (!token) return;
  getMe(token);
  // or even
  // if (token) getMe(token);
}, [token, getMe]);

return !token ? (
  <Navigate to="/auth/login" />
) : (
  <RootStyle>
    <DashboardNavbar onOpenSidebar={() => setOpen(true)} />
    <DashboardSidebar
      isOpenSidebar={open}
      onCloseSidebar={() => setOpen(false)}
    />
    <MainStyle>
      <Outlet />
    </MainStyle>
  </RootStyle>
);
  • Related