Home > Net >  How to navigate to other page when location.state is null
How to navigate to other page when location.state is null

Time:11-14

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.

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

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

Any help will be appreciated

CodePudding user response:

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];

CodePudding user response:

You will need to split the logic between issuing the imperative navigation action as a side-effect, and returning null from the component so you are not accidentally accessing null or undefined state.

Example:

useEffect(() => {
  if (location.state === null) {
    navigate("/");
  }
}, []);

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

if (!location.state) {
  return null;
}

Alternatively you could simply return the Navigate component instead. Just ensure that any and all React hooks are unconditionally called prior to any early returns from the React function body.

Example:

...

if (location.state === null) {
  return <Navigate to="/" />;
}

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