Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

261
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda