Home > Blockchain >  get useLocation props from Route : Uncaught TypeError: Cannot read properties of null (reading '
get useLocation props from Route : Uncaught TypeError: Cannot read properties of null (reading '

Time:05-03

I'm new to reactjs, I want to access to my component Bdc using two ways first when I click on a button in another component and the other way when I access the component using its path directly in search bar.

First way is working using useLocation

<Button 
   variant="contained" 
   onClick={() => navigate("/nouveauBdc", {state: {id: '', isNew: true}})}>
         NOUVEAU BON DE COMMANDE
 </Button>

In my component I can read state sent from navigate("/nouveauBdc", {state: {id: '', isNew: true}})

but the second way when I put the path of my component in search bar http://localhost:3001/nouveauBdc I got this error

Uncaught TypeError: Cannot read properties of null (reading 'isNew')

Bdc component : here is the line from where I got the error :

React.useEffect(() => {
    setBdcState(location.state as BdcProps);
  }, [location])

React.useEffect(() => {
    if(!bdcState.isNew){
      //get data
    }
  }, [bdcState.isNew]) // the line error

my Routes I put the Link to pass the state from here but is not working

<BrowserRouter>
    <Routes>
      <Route path="/nouveauBdc" element={<ProtectedRoutes/>}>
         <Route path="/nouveauBdc" element={<Bdc />} />
      </Route>
          
      <Route path="*" element={<h1>404 - Page non trouvée</h1>} />
      <Route path="/accessDenied" element={<h1>403 - Accès interdit</h1>} />
    </Routes>
    <Link to={'nouveauBdc'} state={{ state: {id: '', isNew: true} }} >Page 1</Link>

  </BrowserRouter>,

ProtectedRoutes.tsx

const user = () => {
    if(userAuth)){
      return(
        <Outlet/>
      );
    } else {       
      return(
        <Navigate to="/accessDenied"/>
      );          
    } 
  }
  
  return(
    <div>
      {user()}
    </div>
    );

Please is there any solution to send state as well when access component directly (search bar)

CodePudding user response:

You cannot set the state directly from the location bar, it will always be null (and null, of course, doesn't have any properties, so you get the error).

If you want to display the component when the location is inserted in the URL bar, you should use location.search instead. That will add a query to your url, such as ?bcdState=new which you can read when the component loads similar to location.state.

  • Related