1

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. This 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 is there any help to avoid or fix this error?

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, but I will try to see the docs on this.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
ayex
  • 65
  • 7

1 Answers1

0

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);
MrCode
  • 63,975
  • 10
  • 90
  • 112
  • thanks a lot,you are very awesome with your explanation,detail and provided link can you give me any idea on protecting the profile route.i mean when users are not logged in they can not view the profile route instead they are given a text saying they should log in.i tried using the protectedroute and with in i request the server but it need a body like login so no luck tried using useRef and useEffect by checking for changing success state again with no luck. – ayex Jan 22 '23 at 21:17