Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

634
Vistas
You should call navigate() in a React.useEffect(), not when your component is first rendered

I am new to ReactJS. On Initial Load of Page, I want to check if the state is null, then I want to redirect to another login Page

Here's the Component Code:

export default function Addblousesalwar() {
  const navigate = useNavigate();
  const { state } = useLocation();
  console.log(state)   //null
  if(state === null || state === undefined){
    navigate("/login")
  }

But It shows error:

You should call navigate() in a React.useEffect(), not when your component is first rendered.

I tried via useEffect also. But the useEffect doesn't get executed.

useEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, []);



useEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, []);

I tried this also

 useEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, [state]);

This useeffect also not triggering Please Help me with some solutions

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

you should use useEffect after all asynchronous function, here the example:

const userInfo = localStorage.getItem('user-info');
    
async function signUp() 
{
    let item = {name, password, email};
    console.warn(item);
    let result = await fetch("http://127.0.0.1:8000/api/register",{
            method: 'POST',
            body: JSON.stringify(item),
            headers: {
                "content-type": 'application/json',
                "Accept": 'application/json'}
        })
    result  = await result.json();
    console.warn('result', result);
    localStorage.setItem("user-info",JSON.stringify(result));
    navigate("/add");
}

useEffect(() => {
    if (userInfo){
     navigate("/add")   
    }
},[])
about 4 years ago · Juan Pablo Isaza Denunciar

0

As mentioned in the comments, you should really provide a codesandbox or at least more code.

That being said, I'm gonna guess that 'state' is not undefined nor is it null, it's an [] (that's usually what it's defaulted to const [state, setState] = useState([]) ) and that's why you think it's not working.

try

useEffect(() => {
    if(!state.length){
      navigate("/")
    }
  }, []); 
about 4 years ago · Juan Pablo Isaza Denunciar

0

export default function Addblousesalwar() {
    const navigate = useNavigate();
    const { state } = useLocation();

    //I used useLayoutEffect instead of useEffect and the below turned into warning instead of an error

    //You should call navigate() in a React.useEffect(), not when your component is first rendered.

     useLayoutEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, []);
 }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda