Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!