Home > Mobile >  The written link and condition is correct but the page does not move
The written link and condition is correct but the page does not move

Time:04-24

I want my login page to go to the contact confirmation page if I get number 200 from the server, but it does not work. Where is my mistake?

 const [form, setForm] = useState({});

 async function checkLogin() {
     try {
         const response = await axios({
             url: 'https://api.bms-go2tr.com/api/v1/check',
             method: 'POST',
             data: form
         });

         if (response.status == 200) {
             return <Link to="/Verification"/>
         }
     } catch (error) {
         if (error.status == 493) {
             return <Link to="/Verification" />
         } else {
             alert(error.response.data.message)
         }
     }

CodePudding user response:

<Link> Component is used to create link in your application but it don't navigate to that link. For Navigation you can use useNavigate() hook or <Navigate> Component(if you use react router v6).

Solution: Instead of <Link to="/Verification" /> use <Navigate to="/Verification" />.

CodePudding user response:

You cant return JSX like this in a callback and expect it to be rendered into the DOM. In callback handlers like this you are wanting to issue an imperative navigation action (i.e. using the navigate function), versus a declarative action (i.e. rendering a Link or Navigate component).

Use the useNavigate hook to access the navigate function and replace the Link with a call to navigate.

Example:

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

...

const navigate = useNavigate();
const [form, setForm] = useState({});

async function checkLogin() {
  try {
    const response = await axios({
      url: 'https://api.bms-go2tr.com/api/v1/check',
      method: 'POST',
      data: form
    });

    if (response.status == 200) {
      navigate("/Verification");
    }
  } catch (error) {
    if (error.status == 493) {
      navigate("/Verification");
    } else {
      alert(error.response.data.message);
    }
  }
}
  • Related