1

I am trying to navigate back to a protected route after a user logs in. Lets say a blog website where a user has to log in before creating a post.

When they try to access the /create url they are redirected to /login url. I want to be redirected to a /create url or to say so the requested url.

This is what i tried but it is not working as expected

Login Component

const navigate = useNavigate()
const location = useLocation()
let { from } = location.state || { from: { pathname: "/" } };
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")


async function login(e) {
    e.preventDefault()
    console.log(email, password);
    let data = { email, password }
    let result = await fetch("http://127.0.0.1:3000/login", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
            Authorization: localStorage.token
        },
        body: JSON.stringify({ session: data })
    })
    result = await result.json()
    if (result.error) {
        return "Failed to fetch"
    } else {
        navigate(from);
        localStorage.setItem("user", JSON.stringify(data.email))
        localStorage.setItem("token", result.jwt)
        console.log(data.email);
    }
}

Protected Route

import React, { Component } from "react";
import { Route, Navigate } from "react-router-dom";


function PrivateRoute({ component: Component, ...rest }) {

    let userToken = localStorage.getItem("token")

    return userToken ? <Component /> : <Navigate to="/login" />;
}

export default PrivateRoute;
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Missing is grabbing the current location to send in route state in the `Navigate` component. See the `react-router-dom@6` section of the duplicate target. – Drew Reese Oct 27 '22 at 15:58

0 Answers0