Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to navigate to other page when location.state is null

I have a react application where I pass state via react router and access the state using location in the target component/page. It works perfect, however when I close the tab and paste the exact same url to that page in another tab it crashes and says Cannot read properties of null (reading '1'). This is how I am accessing the state:

const { filter, mode } = location?.state[1];

I want to navigate to home page if the location state is null.

I have tried the following but does not seem to work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if (location.state === null) {
  navigate("/");
}

const { filter, mode } = location?.state[1];

Any help will be appreciated

>Solution :

The code is still running after navigate if you don’t return

if (location.state===null) {
  navigate("/");
  return null;
}

const { filter, mode } = location?.state[1];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading