Home > Blockchain >  redirecting in react router 6 and reactjs 17
redirecting in react router 6 and reactjs 17

Time:12-26

I want to redirect the user after successful login to the home page, But nothing works. This is my Login.js component Also, I could not get parameter URL in class-based components and I was forced to use functional component and I use let params=useParams(); to get URL parameters

function Login(props) {
  const verify = (e = null) => {
    fetch("http://localhost:8000/api/login/", {
      method: "post",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        mobile,
        securityCode,
      }),
    })
      .then((response) => response.json())
      .then((data) => {
        let result = data.result;
        let message = data.message;
        if (result === "success") {
          clearInterval(sms_interval);
          setToken(data.data);
          // props.history.push('/');  // not works
          useHistory().push("/"); // return this error :  React Hook "useHistory" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
          return <Home />; // not works
          return <Navigate to='/' />; //not works
          return false;
        } else {
          sms_alert_element.classList.add("alert-danger");
          sms_alert_element.innerText = message;
        }
      });
    return false;
  };
}

CodePudding user response:

The useHistory hook is no longer present with React Router 6.

Try to use the useNavigate hook and convert the function to use async / await:

import { useNavigate } from "react-router-dom";

function Login(props) {
  const navigate = useNavigate();

  const verify = async (e = null) => {
    try {
      const response = await fetch("http://localhost:8000/api/login/", {
        method: "post",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          mobile,
          securityCode,
        }),
      });
      const data = await response.json();
      let result = data.result;
      let message = data.message;
      if (result === "success") {
        clearInterval(sms_interval);
        setToken(data.data);
        navigate("/");
      } else {
        sms_alert_element.classList.add("alert-danger");
        sms_alert_element.innerText = message;
      }
      return false;
    } catch (err) {
      console.log(err);
    }
  };
}

  • Related