EN VI

Javascript - Not redirecting to the required link?

2024-03-13 15:30:06
How to Javascript - Not redirecting to the required link

The problem is that, whenever I try to checkout, if I am not logged in, it goes to the link "http://localhost:3000/login?redirect=shipping" to login and then goes to the shipping site where one has to enter address etc.

It redirects to "http://localhost:3000/login/shipping" but it should redirect to "http://localhost:3000/shipping".

The code is:

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { login } from "../../redux/action/userAction";

const Login = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const location = useLocation();
  const navigate = useNavigate();

  const redirect = location.search ? location.search.split("=")[1] : "/";
  console.log(`Login Redirect ${redirect}`); // here it take "shipping" from redirect variable

  const dispatch = useDispatch();
  const userLogin = useSelector((state) => state.userLogin);

  const { loading, error, userInfo } = userLogin;
  // dispatch(login({ email, password }));

  useEffect(() => {
    if (userInfo) {
      navigate(redirect);
    }
  }, [userInfo, redirect]);

  const sumbitHandler = (e) => {
    e.preventDefault();
    dispatch(login(email, password));
  };

  return (
    <div className="flex flex-col justify-center mx-6 my-6">
      <div className="hidden"></div>
      <div className="flex flex-col gap-10">
        {error && (
          <h1 className="text-center bg-red-500 text-red-600 text-sm py-4 w-full">
            {error}
          </h1>
        )}
        <div className="flex flex-col gap-6">
          <h1 className="text-3xl font-medium">Log In to Exclusive</h1>
          <p className="text-sm">Enter your details below</p>
        </div>
        <div className="flex flex-col gap-4">
          <form onSubmit={sumbitHandler} autoComplete="off">
            <div className="flex flex-col gap-6">
              <div>
                <input
                  type="email"
                  placeholder="Enter Email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="text-sm border-b-[1px] border-black/[60%] w-full px-1 py-3"
                  autoComplete="off"
                />
              </div>
              <div>
                <input
                  type="password"
                  placeholder="Password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="text-sm border-b-[1px] border-black/[60%] w-full px-1 py-3"
                  autoComplete="off"
                />
              </div>
              <div className="my-">
                <button
                  className="text-base text-white bg-black py-4 w-full rounded-full"
                  type="submit"
                >
                  Login
                </button>
>               </div>
            </div>
          </form>
          <div>
            <h1 className="text-center text-xs text-black/[60%]">
              Don't have an account?{" "}
              <span className="hover:underline">
                <Link
                  to={redirect ? `/signup?redirect=${redirect}` : "/signup"}
                >
                  SingUp
                </Link>
              </span>
            </h1>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;

I tried to do manual navigation like giving direct path to "/shipping" but it didn't work well.

Solution:

You are "redirecting" to "shipping" which is a relative path since it doesn't start with a leading "/" character. Relative paths will get appended to the current path, e.g. if the current path is "/login", then navigate("shipping") will navigate to "/login/shipping".

Read the redirect search param and ensure it is an absolute path that has a leading "/", e.g. "/shipping".

const Login = () => {
  ...

  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  const redirect = `/${searchParams.get("redirect") ?? ""}`; // "/shipping"
  
  ...

  useEffect(() => {
    if (userInfo) {
      navigate(redirect, { replace: true });
    }
  }, [userInfo, redirect]);
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login