Skip to content
Advertisement

Nextjs UseEffect is not rendering on route change

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!

Advertisement

Answer

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

useEffect(() => {
   ...
}, [isVender, router.pathname])
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement