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

I have a problem passing props from a state to the child

This is the Login component where I created the authentication state with the token as false, and after login convert as true

function Login() {
  const [user, setUser] = useState({ name: '', email: '' });
  const [error, setError] = useState('');
  const [auth, setAuth] = useState({ token: false })
  console.log(auth)
  const Login = (details) => {
    console.log(details);
    if (
      details.name === adminUser.name &&
      details.email === adminUser.email &&
      details.password === adminUser.password
    ) {
      console.log('Logged in');
      setAuth({
        token: true,
      })

This works perfectly fine, but now when I try to pass it to the PrivateRoute component, the auth is undefined

const PrivateRoutes = ({ auth }) => {
  console.log(auth)
  return (
    auth ? <Outlet/> : <Navigate to="/login"/>
  )
}

Also this is my App.jsx

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

function App() {
  return (
    <Routes>
      <Route element={<PrivateRoutes />}>
        <Route path="/*" element={<MainPage />} />
      </Route>
      <Route path="/login" element={<Login />} />
    </Routes>
  );
}

What do I need to change to get the data from the state and my guard functionality to work?

>Solution :

The auth state should be in a common ancestor so it can be passed down as props.

Example:

function App() {
  const [auth, setAuth] = useState({ token: false });

  return (
    <Routes>
      <Route element={<PrivateRoutes auth={auth} />}>
        <Route path="/*" element={<MainPage />} />
      </Route>
      <Route path="/login" element={<Login setAuth={setAuth} />} />
    </Routes>
  );
}
const PrivateRoutes = ({ auth }) => {
  return auth.token ? <Outlet/> : <Navigate to="/login" replace />;
}
function Login({ setAuth }) {
  const navigate = useNavigate();

  const [user, setUser] = useState({ name: '', email: '' });
  const [error, setError] = useState('');

  const login = (details) => {
    if (
      details.name === adminUser.name &&
      details.email === adminUser.email &&
      details.password === adminUser.password
    ) {
      setAuth({ token: true });
      navigate(/* new target path */, { replace: true });

    ...
  }

  ...
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