Hi, I am facing a bug in my code....please help

Question:
The problem is when username and password matches with the customer table’s username and password it should route to the vedios page else error page but it redirects to the error page only …please help

import { useFormik } from "formik";
import axios from "axios";
import { useState } from "react";
import { useNavigate } from "react-router-dom";

export default function TutorialLogin() {
  const [users, setUsers] = useState([]);
  const navigate = useNavigate();
  const formik = useFormik({
    initialValues: {
      UserName: "",
      Password: "",
    },

    onSubmit: (customer) => {
      axios({
        method: "get",
        url: "http://127.0.0.1:5050/customer",
      }).then((response) => {
        setUsers(response.data);
        for (var user of users) {
          if (
            user.userName === customer.UserName &&
            user.password === customer.Password
          ) {
            navigate("/vedios");
          } else {
            navigate("/invalid");
          }
        }
      });
    },
  });
  return (
    <div>
      <h1>Welcome To Tutorial Login Page</h1>

      <form onSubmit={formik.handleSubmit}>
        <dl>
          <dt>User name</dt>
          <dd>
            <input
              type="text"
              onChange={formik.handleChange}
              name="UserName"
            ></input>
          </dd>
          <dt>Password</dt>
          <dd>
            <input
              type="password"
              onChange={formik.handleChange}
              name="Password"
            ></input>
          </dd>
        </dl>
        <button type="submit" className="btn btn-primary">
          Login
        </button>
      </form>
    </div>
  );
}

customer collection

{
  "_id": {
    "$oid": "65887ca68d1d519e7b3214a7"
  },
  "userId": "1",
  "userName": "Rashi",
  "password": "rashi@111",
  "Age": "21",
  "email": "rashi@gmail"
}

Please help me with this error

Axios request is async, so, when you make an axios request, it returns a promise (which means the code inside .then() runs async). I’d suggest fix this in your onSubmit function, I made some other changes which I believe will help you too.

onSubmit: (customer) => {
  axios({
    method: "get",
    url: "http://127.0.0.1:5050/customer",
  }).then((response) => {
    const users = response.data;
    let isValidUser = false;

    for (var user of users) {
      if (
        user.userName === customer.UserName &&
        user.password === customer.Password
      ) {
        isValidUser = true;
        break; // Break the loop if a valid user is found
      }
    }

    if (isValidUser) {
      navigate("/vedios");
    } else {
      navigate("/invalid");
    }
  });
},
2 Likes

@WindLother Thank you so much for the response…Actually it was working fine yesterday now again the code break…

import { useFormik } from "formik";
import axios from "axios";
import { useState } from "react";
import { useNavigate, Link } from "react-router-dom";
import { useCookies } from "react-cookie";

export default function TutorialLogin() {
  const [users, setUsers] = useState(["UserName", "Password"]);
  const navigate = useNavigate();

  const [cookies, setCookies, removeCookies] = useCookies(["UserName"]);
  const formik = useFormik({
    initialValues: {
      UserName: "",
      Password: "",
    },

    onSubmit: async (customer) => {
      await axios({
        method: "get",
        url: "http://127.0.0.1:5050/customer",
      }).then((response) => {
        setUsers(response.data);
        let isValidUser = false;

        for (var user of users) {
          if (
            user.userName === customer.UserName &&
            user.password === customer.Password
          ) {
            isValidUser = true;

            setCookies("username", customer.UserName, {
              expires: new Date("2023-12-28"),
            });
            break;

            // Exit the function early since a valid user is found
          }

          // If the loop completes without finding a valid user
        }
        if (isValidUser) {
          navigate("/invalid");
        } else {
          navigate("/videos");
        }
      });
    },
  });

  return (
    <div>
      <h1>Welcome To Tutorial Login Page</h1>

      <form onSubmit={formik.handleSubmit}>
        <dl>
          <dt>User name</dt>
          <dd>
            <input
              type="text"
              onChange={formik.handleChange}
              name="UserName"
            ></input>
          </dd>
          <dt>Password</dt>
          <dd>
            <input
              type="password"
              onChange={formik.handleChange}
              name="Password"
            ></input>
          </dd>
        </dl>
        <button type="submit" className="btn btn-primary">
          Login
        </button>
        <p>
          <Link to="/register">New User Click Here to Register</Link>
        </p>
      </form>
    </div>
  );
}

can you please check once …I tried with the changes you suggested…but its not working…Thanks in Advance! And Happy New Year in Advance!

Let’s… try another approach.

Use await to fetch user data and instead of setting the users to state and then looping, I think it’s better if you loop directly over the fetched data (fetchedUsers ). This propably will correct the asynchronous state update issue.

I insert a error handling too (so if any errors are made tell them to me)

Try this and see if it works.

onSubmit: async (customer) => {
  try {
    const response = await axios.get("http://127.0.0.1:5050/customer");
    const fetchedUsers = response.data;
    let isValidUser = false;

    for (var user of fetchedUsers) {
      if (
        user.userName === customer.UserName &&
        user.password === customer.Password
      ) {
        isValidUser = true;
        setCookies("username", customer.UserName, {
          path: "/", 
          expires: new Date("2023-12-28")
        });
        break;
      }
    }

    if (isValidUser) {
      navigate("/videos");
    } else {
      navigate("/invalid");
    }
  } catch (error) {
    console.error("Error fetching users:", error);
  }
}
2 Likes

Hi again!..@WindLother Thanks for the quick response…
this one is also not working I am still redirecting to the /invalid

Can you give me the full error?

3 Likes

Hi @WindLother …Its not showing any error…actually I have created two routes if it is not matching the username or password it should redirect to loginErrorComp.js that is the error page else it should go the /videos route …but sometimes even if the credentials are correct still its redirecting to error page and sometimes its just for the fraction of milliseconds it goes to videos and again it reached back to loginpage again…I can see the change in url it goes to /videos and then suddenly back to login

Can you share the link to your repl?

1 Like

yeah sure…I dont know how to do that can I share screnshot?

Just copy the url in the address bar when you are in the repl.

so do I need to paste the code again?..Hi, I am facing a bug in my code....please help - #10 by NateDhaliwal
Like this?

Nono, @WindLother is asking for the repl link, like https://replit.com/@username/Repl-name.
Change username and Repl-name to your username and repl’s name respectively.

I tried the link it showing 404 error

No, I meant changing username in the link I sent with your Replit username, and Repl-name with the name of your repl.
E.g. https://replit.com/@NateDhaliwal/Jackpot.
NateDhaliwal is the username, Jackpot is the repl name.

Yeah I got that I done the changes then I checked the link which I form in the browser that showing 404 error

What is the link you are accessing?

https://replit.com/rashmidhande1/Hi,%20I%20am%20facing%20a%20bug%20in%20my%20code….please%20help

No, the url is not in the forum. It is in replit.com.
Go to your repl in replit.com.
Then, copy the url when you are in the repl.
The repl is where your code is.

https://replit.com/@rashmidhande1

this is what I got…In my repl there is nothing related to my query

What is your repl (code area) name called?