3

I am having problem with a useEffect inside a component which is in every component. I have made some authentication and redirects in that component but I figured that when I use Nextjs link or the go back button from the browser, the Layout useEffect is not re rendering which means it is not checking if the user is logged in for example.

here's my layout component

const Layout = ({ children }) => {

  const router = useRouter()
  const { setAuthenticated, userFromDB, setUserFromDB, setIsVender, isVender } = useContext(AuthContext)

  //cuando hacemos un login el token se guarda en el local storage asi que comprobamos que exista
  useEffect(() => {
    const checkToken = async () => {
      const token = localStorage.getItem('FBIdToken')
      if (token) {
        const decodedToken = jwtDecode(token);
        //si la fecha de expiracion del token supero a la actual, redirect al login
        if (decodedToken.exp * 1000 < Date.now()) {
          setAuthenticated(false)
          router.replace('/login');
        } else {
          if(!userFromDB){
            const user = await getUser(decodedToken.user_id);
            //si encontro un usuario, lo asignamos al context api
            if(user){
              console.log(user)
              //  obtenemos el objecto con los datos del usuario y seteamos en el context si es vendedor o no
              if(typeof user.isVender !== undefined){
                user.isVender ? setIsVender(true) : setIsVender(false);
              }
              setUserFromDB(user);
            }
            setAuthenticated(true)
          }
        }
        console.log('ejecutando');
      } else {
        if(router.pathname !== "/" && 
            router.pathname !== "/download-app" && 
            router.pathname !== "/register" && 
            router.pathname !== "/login"
          ) {
          console.log(router.pathname, 'redirigiendo')
          router.replace('/login')
        }
        
      }
    }
    //comprobamos que haya un token y redirigimos al usuario en base a el
    checkToken();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isVender])


  return (
    <div>
      {children}
    </div>
  )
}

this is how I import it inside the _app.js component

  return (
    <AuthProvider>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </AuthProvider>
  )
}

I hope you can help me, thanks in advance!

2
  • 1
    This: // eslint-disable-next-line react-hooks/exhaustive-deps is almost always an indication that there's a bug in the code. It's probably covering up the bug in your code. Don't do that unless you are sure that you are right and the lint rule is wrong. That effect will only re-run if isVender (whatever that is) changes. Commented Jan 13, 2022 at 17:13
  • I removed it and nothing happened, I think it was because of a warning but is gone now Commented Jan 13, 2022 at 17:47

1 Answer 1

8

If you want useEffect to trigger on router changes, you must add it as a dependancy of your useEffect hook:

useEffect(() => {
   ...
}, [isVender, router.pathname])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I didn't know I could do that with router. You saved me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.