-2
import Navbar from "./components/Navbar"
import Home from "./routes/Home"
import Signup from "./routes/Signup"
import Login from "./routes/Login"
import useAuthContext from "./hooks/useAuthContext"
import { Navigate } from "react-router-dom"
export default function App() {
  const { user } = useAuthContext()
  const router = createBrowserRouter(
    createRoutesFromElements(
      <Route path="/" element={<Navbar />}>
        <Route index element={!user ? <Navigate to="/login" /> : <Home />} />
        <Route path="/signup" element={<Signup />} />
        <Route path="/login" element={<Login />} />
      </Route>
    )
  )
  return <RouterProvider router={router} />
}

First it shows the login page, after I login it will stay on login page. how do I fix this?

I did try many things. it wont worked, i know in v5 I can use redirect component to redirect page.

dscpp
  • 3
  • 2
  • It should work. Are you sure that `user` is not `undefined` or `null`? – Konrad Jan 01 '23 at 20:32
  • 1
    I tried to print out the user. first, it displayed null then after I logged in, I got the user info object. – dscpp Jan 01 '23 at 20:37
  • 2
    There is nothing in this code that would cause it to leave the current `/login` location and got to `/`. You need a `` somewhere in the `` element. – Linda Paiste Jan 01 '23 at 21:02
  • Where does any component navigate ***from*** the `"/login"` route? Is there a `Navigate` component navigating to `"/"` in the app? You may need to [edit] the post to include a more complete [mcve]. – Drew Reese Jan 01 '23 at 21:07
  • 1
    Does this answer help explain the process of redirecting after successful authentication? https://stackoverflow.com/a/66289280/8690857 – Drew Reese Jan 01 '23 at 21:16

1 Answers1

1

You have code that redirects from / to /login when the user is logged out:

<Route index element={!user ? <Navigate to="/login" /> : <Home />} />

You don't have code that redirects from /login to / when the user is logged in.

You need to add a <Navigate> in your /login route, either at the top level or inside of your Login component.

This is the simplest solution:

<Route path="/login" element={user ? <Navigate to="/"> : <Login />} />

(note: Navigate is the v6 equivalent of Redirect)

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102