Home > database >  Having little complication while using useLocation()
Having little complication while using useLocation()

Time:01-23

everyone.i do not now why the same code was working yesterday fine but today not working.i understand why the error happens,but have no idea how to fix it.i am trying to redirect the user to profile component using Navigate comp with a state pass,that works fine,but when a user manually clicks on profile i get the error because i am trying to access the state value that does not exist,since the state value is defined after only redirecting.so,any help to avoid or fix this error?thanks in advance.

react-refresh-runtime.development.js:315 Uncaught TypeError:
 Cannot read properties of null (reading 'mes')

Login.jsx

import { useState } from "react";
import { Link, Navigate, Outlet } from "react-router-dom";
import axios from "axios";
import { FaEye, FaEyeSlash } from "react-icons/fa";

function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [inputType, setInputType] = useState("password");
  const [icon, setIcon] = useState(<FaEye />);
  const [success, setSuccess] = useState("");
  const [result, setResult] = useState(false);

  function handleToggle(e) {
    if (inputType === "password") {
      setInputType("text");
      setIcon(FaEyeSlash);
    } else {
      setInputType("password");
      setIcon(FaEye);
    }
  }

  function handleSubmit(e) {
    e.preventDefault();

    const user = { email, password };
    console.log(`email: ${email}, password: ${password}`);
    axios
      .post("http://localhost:5000/user/login", user)
      .then((res) =>{
      setResult(true);
      setSuccess(`welcome ${res.data.user} you are successfully Logged in!`);
       console.log(result);
      }
      )
      .catch((err) => {
        //console.log(`ERROR is ${err}`);
        setResult(false);
        console.log(result);
        setSuccess("Incorrect password or email");
      });
  }

  if(result){
    console.log(result);
   return <Navigate to="/profile" state={{mes: success }} />
  }

  return (
    
    <form onSubmit={handleSubmit}>
      <div className="text-center text-lg text-red-500 font-semibold">{success}</div>
      <div className="h-auto w-5/12 border mx-auto rounded-2xl mt-3 ">
        <div className="h-2 bg-indigo-400 rounded-t-2xl mb-5 "></div>
        <div className="font-bold text-2xl text-center">Sign In</div>
        <div className="px-16">
          <div className="mt-5 ">
            <label htmlFor="email" className="block font-semibold  ">
              Email address
            </label>
            <input
              type="email"
              className="border h-5 w-full px-3 py-5 rounded-md focus:outline-2 focus:outline-blue-600"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Enter email"
              id="email"
              required
            />
          </div>

          <div className="relative ">
            <label
              htmlFor="pass"
              className="block font-semibold mt-5"
            >
              Password
            </label>
            <input
              type={inputType}
              className="border h-5 w-full px-3 py-5 rounded-md focus:outline-2 focus:outline-blue-600"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter password"
              id="pass"
              required
            />
            <span className="absolute top-9 right-6" onClick={handleToggle}>
              {icon}
            </span>
          </div>

          <div className="">
            <button
              type="submit"
              className="mt-5 text-white bg-blue-600 border h-10 w-full py-2 rounded-md"
            >
              Submit
            </button>
          </div>
          <div className="flex justify-around">
            <p className="mb-5 mt-3 text-left">
              New here?
              <Link to="/sign-up" className="text-blue-600">
                Register
              </Link>
            </p>
            <p className="mb-5 mt-3 text-right ">
              Forgot
              <Link to="/password-reset" className="text-blue-600">
                password?
              </Link>
            </p>
          </div>
        </div>
      </div>
    </form>
  );
}
  

export default Login;

Profile.jsx

import { useState } from "react";
import { useLocation } from "react-router-dom";

function Profile() {
  const location = useLocation();
  const msg = location.state.mes;
  const [success, setSuccess] = useState(msg);
  const [cancel, setCancel] = useState("X");
  const [name, setName] = useState(
    "h-10 flex justify-around items-center bg-green-200 text-black"
  );
  function handleClick() {
    setSuccess("");
    setCancel("");
    setName("");
  }
  return (
    <>
    
      <div className={name}>
        {success}
        <button onClick={handleClick}>{cancel}</button>
      </div>
      profile
    </>
  );
}

export default Profile;

i have not tried anything,because i am having a headache,but i will try to see the docs on this.

CodePudding user response:

Simply use Optional Chaining to check if location.state.mes exists. If location.state or location.state.mes doesn't exist then default to an empty string in the useState() call.

  const msg = location.state?.mes; // msg will either be undefined or the message value
  const [success, setSuccess] = useState(msg == undefined ? '' : msg);
  • Related