Gajanan Shinde
Gajanan Shinde

Reputation: 133

Uncaught Error: useNavigate() may be used only in the context of a <Router> component

Hello guys facing this and dont know how to solve this Tried everything to resolve this is this because of latest router library version just show you the patch of code

import "./App.css";
import Form from "./Form";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useNavigate,
  
} from "react-router-dom";
import { useEffect, useState } from "react";
import { app } from "./firebase-config";
import {
  getAuth,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
} from "firebase/auth";
import Home from "./Home";

function App() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const[data,setData]=useState({});
    let navigate = useNavigate();

  useEffect(() => {
    let authToken = sessionStorage.getItem("Auth Token");

    // if (authToken) {
    //   // navigate("/home");
    //   window.location.href = "/home";
    console.log(data);
    // }
  }, []);
  const handleAction = (id) => {

    console.log(id);
    const authentication = getAuth();
    if (id === 2) {
      createUserWithEmailAndPassword(authentication, email, password).then(
        (response) => {
          sessionStorage.setItem(
            "Auth Token",
            response._tokenResponse.refreshToken
          );
          setData(response._tokenResponse);
           navigate('/home');
          window.location.href = "/home";

          console.log(response);
        }
      );
    } else if (id === 1) {
      console.log("response");

      signInWithEmailAndPassword(authentication, email, password).then(
        (response) => {
          console.log(response);
          setData(response._tokenResponse);

          sessionStorage.setItem(
            "Auth Token",
            response._tokenResponse.refreshToken
          );
           navigate("/home");
          // window.location.href = "/home";
        }
      );
    }
  };
  return (
    <Router>
      <div className="App">
        <>
          <Routes>
            <Route
              path="/login"
              element={
                <Form
                  title="Login"
                  setEmail={setEmail}
                  setPassword={setPassword}
                  handleAction={() => handleAction(1)}
                  data={data}
                />
              }
            />
            <Route
              path="/register"
              element={
                <Form
                  title="Register"
                  setEmail={setEmail}
                  setPassword={setPassword}
                  handleAction={() => handleAction(2)}
                  data={data}
                />
              }
            />
            <button onClick={() => navigate(-1)}>go back</button>

            <Route path="/home" element={<Home data={data} />} />
          </Routes>
        </>
      </div>
    </Router>
  );
}

export default App;

also got this error on console

Uncaught Error: useNavigate() may be used only in the context of a component. at invariant (index.tsx:19) at useNavigate (index.tsx:507) at App (App.js:23) at renderWithHooks (react-dom.development.js:14985) at mountIndeterminateComponent (react-dom.development.js:17811) at beginWork (react-dom.development.js:19049) at HTMLUnknownElement.callCallback (react-dom.development.js:3945) at Object.invokeGuardedCallbackDev (react-dom.development.js:3994) at invokeGuardedCallback (react-dom.development.js:4056)

Little Help is appriciated

Everything works fine when i remove useNavigate()

Upvotes: 2

Views: 20144

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85191

Your <Router> needs to be higher up the component tree than where you use useNavigate, but that's not the case currently. You're calling useNavigate in App, but the Router is inside App, not higher up the tree from App.

You'll probably want to split your components up. Something like this:

function App() {
  return (
    <Router>
      <SomeOtherComponent/>
    </Router>
  )
}

function SomeOtherComponent() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [data,setData] = useState({});
  let navigate = useNavigate();

  // ... etc. Code is exactly the same as yours, just no Router in the return

  return (
    <div className="App">
      <>
        <Routes>
          // etc
        </Routes>
      </>
    </div>
  )
}

Upvotes: 3

Related Questions