Home > other >  Check username, password - Login Form using React Hooks
Check username, password - Login Form using React Hooks

Time:03-19

I want to create a login form with array data UsersData.js:

const users = [
  {
    username: 'admin1',
    password: '12345678'
  },
  {
    username:'admin2',
    password:'012345678'
  }
];

and Login.js looks something like this:

import React, {useState} from 'react';
import { users } from 'UsersData';

  function Login() {
      const [data, setData] = useState({
        username: '',
        password: ''
      });
          
      const {uname, pass} = data;
      const checkUser = () => {
        const usercheck = users.find(user => (user.username === uname && user.password === pass));
        if(usercheck) {
          console.log("Login successful");
        }else {
          console.log("Wrong password or username");
        }
        // console.log(uname);
        console.log(usercheck);
      }

      const changeHandler = (e) => {
        setData({...data, [e.target.name]:[e.target.value]})
      }
      const handleSubmit = (e) => {
        e.preventDefault();
        checkUser();
        console.log(checkUser());
      }

    return (
      <div className="login-bg">
        <div className="card">
          <form className='loginForm'
          onSubmit={handleSubmit}
          >
          <div className="input-text">
              <input
                type="text"
                name="username"
                value={uname}
                placeholder="Username"
                aria-describedby="inputGroupPrepend2" required
                onChange={changeHandler}
              />
          </div>
          <div className="input-text">
            <input
              type="password"
              name="password"
              value={pass}
              placeholder="Password"
              aria-describedby="inputGroupPrepend2" required
              onChange={changeHandler}
            />
            
          </div>
          <div className="buttons">
              <button type="submit" className="btn btn-warning btn-block">
                Login
              </button>
          </div>
        </form>
        </div>
     </div>
    )
  }
export default Login;

So the above code only check whether the username and password fields entered in the form match the name and password of single record in the array of objects of UsersData.js the above code is working fine.I wrote checkUser() function but the result is not true.

Please show an instance of how it is done. Sorry, I'm new to ReactJS so I'm a bit confused, hope you can help. Thanks

CodePudding user response:

Hey autumnha So with the way you are destructuring firstly needs to be the values that you are pulling from data obj

Let me know if this is what your goal is ?

const { username, password } = data

we now have the local component state of username and data

const checkUser = (users) => {
        const usercheck = users.find(user => (user.username === username 
        && user.password === password))
         return usercheck ? console.log('successfully logged in') : 
        console.log('wrong credentials')
 }

we then invoke the function

checkUser(users)

CodePudding user response:

I think you can use map() and some() to achieve that goal. As you are checking if one of the user is in the array, that will generate an array with true, and false, like [false, false, true], etc.

Therefore, the most straightforward solution is to map through the users with your input values and then check authentication by some().

const onCheck = () => {
  const {uname, pass} = data;
  const isAuthenticated = users.map(user => user.username === uname && user.password === pass);

  return isAuthenticated.some();
}


if(onCheck()) {
   console.log("Login successful");
}else {
   console.log("Wrong password or username");
}

CodePudding user response:

your logic here is also not correct this is how the event handled must be

  import { useEffect, useState } from "react";
import "./styles.css";
const users = [
  {
    username: 'admin1',
    password: '12345678'
  },
  {
    username:'admin2',
    password:'012345678'
  }
];
export default function App() {
  const [data, setData] = useState({
    username: '',
    password: ''
  });
  const changeHandler = (e) => {
    setData({...data, [e.target.name]: e.target.value})
  }

  const checkUser = () => {
    const usercheck = users.find(user => (user.username === data.username && user.password === data.password));
    if(usercheck) {
      console.log("Login successful");
    }else {
      console.log("Wrong password or username");
    }
    // console.log(uname);
    console.log(usercheck);
  }


  useEffect(() => {
checkUser(users)
  }, [data.username, data.password])

  console.log(data)
  return (
    <div className="App">
      <div className="input-text">
              <input
                type="text"
                name="username"
                value={data.username}
                placeholder="Username"
                aria-describedby="inputGroupPrepend2" required
                onChange={changeHandler}
              />
          </div>
          <div className="input-text">
            <input
              type="password"
              name="password"
              value={data.password}
              placeholder="Password"
              aria-describedby="inputGroupPrepend2" required
              onChange={changeHandler}
            />
            
          </div>
    </div>
  );
}

enter image description here

  • Related