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