yangcodes
yangcodes

Reputation: 281

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')

Upvotes: 1

Views: 813

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29305

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.

Upvotes: 1

Related Questions