I'm attempting to pass props to a custom route component that I've called 'PrivateRoute'. The purpose of this component is to verify if a user is signed in. After a user signs in, or their token is verified, then they can safely be assumed to be logged in and therefore the token doesn't need to continue getting checked by the backend - meaning I can update my overall app state.
As an aside, I don't want to use Context or Redux here.
As a result, I'm setting my state in my 'App.js' file, and attempting to pass it into my component, like so:
const App = () => {
const [auth, setAuth] = useState(false)
return (
<Router>
<Routes>
<Route path="/dashboard/details" auth={auth} setAuth={setAuth} element={<PrivateRoute><DashboardDetails /></PrivateRoute>} />
</Router>
);
}
export default App;
And then accessing them in my PrivateRoute.js file like so:
const PrivateRoute = ({ props, children }) => {
const { auth, setAuth } = props
const isAuthenticated = // Fetch auth token
if (!isAuthenticated) {
return <Navigate to="/sign-in" replace />
}
if (isAuthenticated) {
// Backend call goes here....
return children
}
}
export default PrivateRoute
This is returning props as undefined (full error message below) - but I figured I should just be able to pass them into the PrivateRoute component and access them that way - since the props aren't passed into the children and they aren't necessary for rendering.
PrivateRoute.js:10 Uncaught TypeError: Cannot destructure property 'auth' of 'props' as it is undefined.
Does anyone have any suggestions?
CodePudding user response:
You passed auth prop to Route
not PrivateRoute
. so it should be
<Route
path="/dashboard/details"
element={
<PrivateRoute auth={auth} setAuth={setAuth}>
<DashboardDetails />
</PrivateRoute>
}
/>