Home > Mobile >  ReferenceError: navigate is not defined
ReferenceError: navigate is not defined

Time:07-08

I'm new in reactjs and I have a new project. I make a register, login function with firebase, and all is ok, but when I try to open a new page for example dashboard when the user is logged have this error

ReferenceError: navigate is not defined

I'm new with the routes in react, what can be a problem?

import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { auth, logInWithEmailAndPassword, sendPasswordReset, signInWithEmailAndPassword, signInWithGoogle } from "./firebase";
import { useAuthState } from "react-firebase-hooks/auth";

function Login() {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [user, loading, error] = useAuthState(auth);
    const navigate = useNavigate();
    
}

function Modal() {

    const handleOKClick = () => {
        setModalOn(false)
    }
    const handleCancelClick = () => {
        setModalOn(false)
    }
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [user, loading, error] = useAuthState(auth);
    const Modal = props => {
        if (!props.show){
          return null
        }
    }
    
    useEffect(() => {
      if (loading) {
        // maybe trigger a loading screen
        return;
      }
      if (user) navigate('/Dashboard');
    }, [user, loading]);
         return (
            <div>
                **This code are a form, is not important**
            </div>
 }
      
 export default Modal

CodePudding user response:

navigate is not defined in function/component or in lexical scope Also need to rearrange as React recommends. Keep hooks at top of function.

const Modal = (props) => {
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [user, loading, error] = useAuthState(auth);

  useEffect(() => {
    if (loading) {
      // maybe trigger a loading screen
      return;
    }
    if (user) navigate("/Dashboard");
  }, [user, loading]);

  const handleOKClick = () => {
    setModalOn(false);
  };
  const handleCancelClick = () => {
    setModalOn(false);
  };

  if (!props.show) {
    return null;
  }

  return <div></div>;
};

CodePudding user response:

Move your const navigate = useNavigate(); into the Modal component. At the moment it's in the Login component.

  • Related