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

260
Vistas
Gatsby - location.state 'Cannot read properties of null'

When I navigate from /pageA to /pageB I am passing a prop through Gatsby's Link to render UI information on PageB that I need from PageA.

If the user goes through the flow properly then the application works as expected. The problem happens when the user manually jumps to /pageB from a different page (i.e: changing url from /home to /pageB)

The navigation library that I'm using is gatsby-plugin-transition-link and I am passing the props following the documentation like so

<Link
 to={'/pageB'}
 state={{ fromPageA: true }}
>

My initial idea was if the prop returned null, then navigate back to the previous page cause then we know it didn't come from the correct page.

useEffect(() => {
 console.log(location.state.fromPageA);
 if (location.state.fromPageA === null) {
  navigate('/pageA')
 }
}, []);

The problem is that I can't even check for that because if I console.log it and it's null it immediately crashes my application with the error

Cannot read properties of null (reading 'fromPageA')

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

0

I think what is breaking your current code is the console.log validation, not the if statement. This should work:

useEffect(() => {
 if (location?.state?.fromPageA === null) {
  navigate('/pageA')
 }
}, []);

If you are not using the optional chaining, you can do:

useEffect(() => {
 if (location){
   if(location.state){
     if(!location.state.fromPageA){
        navigate('/pageA')
     }
   }
 }
}, []);

Assuming you are destructuring the location as props in the component constructor. Otherwise, use props.location.

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