Why does redirecting to the homepage have no effect when using React react-router and useNavigate after logging in?
P粉555696738
P粉555696738 2023-08-26 22:34:52
0
1
414
<p>After successful login, I want the user to be redirected to the homepage, I store the user login api request data in a variable called currentUser, so if currentUser is true, it should redirect to the homepage. This is how I handle login requests: </p> <pre class="brush:php;toolbar:false;">export const AuthContextProvider = ({ children }) => { const [currentUser, setCurrentUser] = useState( JSON.parse(localStorage.getItem("users")) || null ); const login = async (inputs) => { const res= await axios.post("https://micacarballo-social-media-api.onrender.com/api/v1/auth/login",inputs,{ }) setCurrentUser(res.data) }; useEffect(() => { localStorage.setItem("users", JSON.stringify(currentUser)); }, [currentUser,login]); const updateUser = async () =>{ const user = JSON.parse(localStorage.getItem("users")) const res= await axios.get("https://micacarballo-social-media-api.onrender.com/api/v1/users/me/",{ headers: { Authorization: `jwt ${user.token}` } }) setCurrentUser(res.data) } return ( <AuthContext.Provider value={{ currentUser, login, updateUser}}> {children} </AuthContext.Provider> ); };</pre> <p>My protected routes:</p> <pre class="brush:php;toolbar:false;">import { AuthContext } from './context/authContext' function App() { const { currentUser } = useContext(AuthContext); const Layout = ()=>{ return( <div> <Navbar /> <div style={{ display: "flex" }}> <LeftBar /> <div style={{ flex: 6 }}> <Outlet /> </div> </div> </div> ) } const ProtectedRoute = ({children}) =>{ if(!currentUser){ return <Navigate to="/login" /> }return children } const router = createBrowserRouter([ { path: "/", element: ( <ProtectedRoute> <Layout/> </ProtectedRoute> ), children :[ { path:"/", element: <Home /> },{ path:"/profile/:id", element:<Profile /> } ] }, { path: "/login", element: <Login />, }, { path: "/register", element: <Register /> }, ]); return ( <div className="App"> <RouterProvider router={router} /> </div> ) } export default App</pre> <p>我的登录页面:</p> <pre class="brush:php;toolbar:false;">const Login = () => { const [inputs, setInputs] = useState({ email: "", password: "", }); const [err, setErr] = useState(null); const [isLoading, setIsLoading] = useState(false); // state variable for loading spinner const navigate = useNavigate() const handleChange = (e) => { setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value })); }; const {login} = useContext(AuthContext) const handleLogin = async (e) => { e.preventDefault(); try { setIsLoading(true); // set loading to true await login(inputs); navigate("/") } catch (err) { setErr(err.response.data); }finally { setIsLoading(false); // set loading back to false } }; return ( <div className='login'> <div className="card"> <div className="left"> <h1>SocialMica</h1> <p> Make connecting with friends easy and fun </p> <span>Dont have an account yet?</span> <Link to="/register"> <button>Register</button> </Link> </div> <div className="right"> <h1>Login</h1> <form action=""> <input type="email" placeholder='email' name='email' onChange={handleChange}></input> <input type="password"placeholder='password' name='password' onChange={handleChange}/> {err && "invalid email or password"} <button onClick={handleLogin} disabled={isLoading}> {isLoading ? <Loading/> : "Login"}</button> </form> </div> </div> </div> ) } export default Login</pre> <p>I don't understand why it doesn't work, after the user logs in and currentUser has the data stored, the login page just refreshes without redirecting and I have to access the homepage manually. I tried changing the navigate to ("/register") in the handleSubmit function of the login page and it works fine, but not with the navigate('/')</p>
P粉555696738
P粉555696738

reply all(1)
P粉797855790

Change your path /home not just / Like

{
    path:"/home",
    element: <Home />
},

It should work fine

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template