React 'load' is not defined no-undef - reactjs

I'm trying to implement Netlify identity with React here, using this guide
But, I get the error 'load' is not defined no-undef
It is referring to this line
load(loginUser(email, password, true))
Here is the code:
import React, { useRef, useLayoutEffect } from 'react';
import { useIdentityContext } from 'react-netlify-identity';
import { navigate } from "#reach/router" // from login tutorial
// log in/sign up example
function Login() {
const { loginUser, signupUser } = useIdentityContext();
const formRef = React.useRef();
const [msg, setMsg] = React.useState('');
const signup = () => {
const email = formRef.current.email.value;
const password = formRef.current.password.value;
signupUser(email, password)
.then(user => {
console.log('Success! Signed up', user);
navigate('/dashboard');
})
.catch(err => console.error(err) || setMsg('Error: ' + err.message));
};
return (
<form
ref={formRef}
onSubmit={e => {
e.preventDefault();
const email = e.target.email.value;
const password = e.target.password.value;
load(loginUser(email, password, true))
.then(user => {
console.log('Success! Logged in', user);
navigate('/dashboard');
})
.catch(err => console.error(err) || setMsg('Error: ' + err.message));
}}
>
<div>
<label>
Email:
<input type="email" name="email" />
</label>
</div>
<div>
<label>
Password:
<input type="password" name="password" />
</label>
</div>
<div>
<input type="submit" value="Log in" />
<button onClick={signup}>Sign Up </button>
{msg && <pre>{msg}</pre>}
</div>
</form>
);
}
export default Login;

Related

my form won't refresh back to initial state or navigate to the feeds page after success full registration i'm i wrong using async?

my form won't refresh back to initial state or navigate to the feeds page after success full registration and now react is telling me Async await is only available in es8 please can i go about this i want the form to provide some kind of feedback after registration like to n avigate to the homepage and clear all field but it's not working
import { Link, useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import {
getAuth,
createUserWithEmailAndPassword,
updateProfile,
} from 'firebase/auth'
import { setDoc, doc, serverTimestamp } from 'firebase/firestore'
import { db } from '../firebase.config'
import OAuth from '../components/OAuth'
function SignUp() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
})
const { name, email, password } = formData
const navigate = useNavigate()
const onChange = (e) => {
setFormData((prevState) => ({
...prevState,
[e.target.id]: e.target.value,
}))
}
const onSubmit = async (e) => {
e.preventDefault()
try {
const auth = getAuth()
const userCredential = await createUserWithEmailAndPassword(
auth,
email,
password
)
const user = userCredential.user
updateProfile(auth.currentUser, {
displayName: name,
})
const formDataCopy = { ...formData }
delete formDataCopy.password
formDataCopy.timestamp = serverTimestamp()
await setDoc(doc(db, 'users', user.uid), formDataCopy)
navigate('/')
} catch (error) {
toast.error('Something went wrong with registration')
}
}
return (
<>
<div className='pageContainer'>
<header>
<p className='pageHeader'>Welcome Back!</p>
</header>
<form onSubmit={onSubmit}>
<input
type='text'
className='nameInput'
placeholder='Name'
id='name'
value={name}
onChange={onChange}
/>
<input
type='email'
className='emailInput'
placeholder='Email'
id='email'
value={email}
onChange={onChange}
/>
<div className='passwordInputDiv'>
<input
type='password'
className='passwordInput'
placeholder='Password'
id='password'
value={password}
onChange={onChange}
/>
</div>
<Link to='/forgot-password' className='forgotPasswordLink'>
Forgot Password
</Link>
<div className='signUpBar'>
<p className='signUpText'>Sign Up</p>
<button className='signUpButton'>
Sign Up
</button>
</div>
</form>
<OAuth />
<Link to='/sign-in' className='registerLink'>
Sign In Instead
</Link>
</div>
</>
)
}
export default SignUp

Error : not able to write anything into React input feild

This is the first web app that im building using react and im completely lost in validating the login and this is the code i follow and im not able to type anything into the field.
The error occurs during validating since previous i used this and works well before i tried to validate.
import React , {Fragment, useState,useEffect} from 'react'
import { useDispatch , useSelector} from 'react-redux'
import {useAlert} from 'react-alert'
import MetaData from '../layouts/MetaData'
import Loader from '../layouts/Loader'
import { Link, useLocation } from 'react-router-dom'
import {userLogin, clearErrors} from '../../actions/users'
import { useNavigate ,useParams} from 'react-router-dom'
const Login = () => {
const dispatch= useDispatch();
const alert=useAlert();
//const [email,setEmail]=useState('');
//const [password,setPassword]=useState('');
const initialValues = { email: "", password: "" };
const [formValues, setFormValues] = useState(initialValues);
const [formErrors, setFormErrors] = useState({});
const [isSubmit, setIsSubmit] = useState(false);
let navigate=useNavigate();
let location =useLocation();
const {isAuthenticated,error,loading}=useSelector(state =>state.auth);
const redirect=location.search ? location.search.split('=')[1] : '/'
useEffect(()=>{
if(isAuthenticated){
navigate(redirect)
}
if(error){
alert.error(error);
dispatch(clearErrors());
}
}, [dispatch, alert, isAuthenticated, error, navigate])
const handleChange = (e) => {
const { name, value } = e.target;
setFormValues({ ...formValues, [name]: value });
};
const loginHandler = (ev) => {
ev.preventDefault()
setFormErrors(validate(formValues));
setIsSubmit(true);
dispatch(userLogin(formValues.email,formValues.password));
}
useEffect(() => {
console.log(formErrors);
if (Object.keys(formErrors).length === 0 && isSubmit) {
console.log(formValues);
}
}, [formErrors]);
const validate = (values) => {
const errors = {};
const regex = /^[^\s#]+#[^\s#]+\.[^\s#]{2,}$/i;
if (!values.username) {
errors.username = "Username is required!";
}
if (!values.email) {
errors.email = "Email is required!";
} else if (!regex.test(values.email)) {
errors.email = "This is not a valid email format!";
}
if (!values.password) {
errors.password = "Password is required";
} else if (values.password.length < 4) {
errors.password = "Password must be more than 4 characters";
} else if (values.password.length > 10) {
errors.password = "Password cannot exceed more than 10 characters";
}
return errors;
};
return (
<Fragment>
{loading ?<Loader></Loader> :(
<Fragment>
<MetaData title={'Login'} />
<div className="row wrapper">
<div className="col-10 col-lg-5">
<form className="shadow-lg" onSubmit={loginHandler}>
<h1 className="mb-3">Login</h1>
<div className="form-group">
<label htmlFor="email_field">Email</label>
<input
type="email"
id="email_field"
className="form-control"
value={formValues.email}
onChange={handleChange}
/>
</div>
<div className="form-group">
<label htmlFor="password_field">Password</label>
<input
type="password"
id="password_field"
className="form-control"
value={formValues.password}
onChange={handleChange}
/>
</div>
<Link to="/password/forgot" className="float-right mb-4">Forgot Password?</Link>
<button
id="login_button"
type="submit"
className="btn btn-block py-3"
>
LOGIN
</button>
<Link to="/register" className="float-right mt-3">New User?</Link>
</form>
</div>
</div>
</Fragment>
)}
</Fragment>
)}
export default Login
Thanks a lot in advance!!
You are missing name prop (attribute) in your JSX.
Due to this your function is failing to update the state with correct values.
const handleChange = (e) => {
const { name, value } = e.target;
// name will be undefined, because you haven't set it.
setFormValues({ ...formValues, [name]: value });
};
Simply Add name and it will work.
<input
type="email"
id="email_field"
name="email"
className="form-control"
value={formValues.email}
onChange={handleChange}
/>
<input
type="password"
id="password_field"
className="form-control"
name="password"
value={formValues.password}
onChange={handleChange}
/>

Two times click is necessary to Login in ReactJS

I am trying to make a Login page and I am successful in some way. So here is my Login component:
import React, { useState, useEffect } from "react";
import Axios from "axios";
import useForm from "../components/LoginForm/useForm";
import validate from "components/LoginForm/validate";
import redtruck from "../assets/img/red-truck.png";
import auth from "../Authentication/auth";
import { withRouter } from "react-router";
const Login = ({ submitForm, history }) => {
const [isSubmitted, setIsSubmitted] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const [login, setLogin] = useState(false);
async function submitForm() {
setIsSubmitted(true);
try {
await fetchLogin(values.email, values.password);
if(login){
auth.login(() => {
history.push("/admin");
});
}
} catch (e) {
auth.login(() => {
history.push("/");
})
}
}
const { handleChange, values, handleSubmit, errors } = useForm(
submitForm,
validate
);
useEffect(() => {
if (localStorage.getItem("user-info")) {
submitForm();
}
}, []);
const fetchLogin = async (email, password) => {
try {
setLoading(true);
const res = await Axios({
method: "POST",
url: `url`,
headers: {
},
data: {
user_email: email,
user_password: password,
},
});
if (res.status === 200) {
setLogin(true);
localStorage.setItem("user-info", JSON.stringify(res.data));
}
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
};
return (
<>
<div>
<div className="form-container">
<div className="form-content-left">
<img className="form-img" src={redtruck} alt="spaceship" />
</div>
<div className="form-content-right">
<h1>SIGN IN</h1>
<form className="form" onSubmit={handleSubmit}>
<div className="form-inputs">
<label htmlFor="email" className="form-label">
Email address
</label>
<input
id="signin-email"
type="email"
name="email"
placeholder="Enter email"
className="form-input"
value={values.email}
onChange={handleChange}
/>
{errors.email && <p>{errors.email}</p>}
</div>
<div className="form-inputs">
<label htmlFor="password" className="form-label">
Password
</label>
<input
id="signin-password"
type="password"
name="password"
placeholder="Password"
className="form-input"
value={values.password}
onChange={handleChange}
/>
{errors.password && <p>{errors.password}</p>}
{login ? "" : <p>The password or the email is wrong</p>}
</div>
<button
variant="primary"
type="submit"
className="form-input-btn"
>
LOGIN
</button>
</form>
</div>
</div>
</div>
</>
);
};
export default withRouter(Login);
So the login state is set to true when email and password are right for the user. Later I want to use it when redirecting page to "/admin". But my problem is I have to click twice to login in the first place. Besides I am not sure, if the catch part is right:
catch (e) {
auth.login(() => {
history.push("/");
})
}
So I would be really glad, if you can give me some hint about it.
Thanks...
it is not that you have to press twice, you can check component state, sometimes React batches setState and then update value. You can look at this setState doesn't update the state immediately

Wrong authentication Login in ReactJS

I am trying to do a Login page. So I have also protected route which is an admin page. So the first page is Login and if the user is successfully logged in, it should be redirect to '/admin'. For this, my Login component is:
import React, { useState, useEffect } from "react";
import Axios from "axios";
import useForm from "../components/LoginForm/useForm";
import validate from "components/LoginForm/validate";
import redtruck from "../assets/img/red-truck.png";
import auth from "../Authentication/auth";
import { withRouter } from "react-router";
const Login = ({ submitForm, history }) => {
const [isSubmitted, setIsSubmitted] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const [login, setLogin] = useState(false);
async function submitForm() {
setIsSubmitted(true);
try {
await fetchLogin(values.email, values.password);
auth.login(() => {
history.push("/admin");
});
} catch (e) {
console.log("wrong pass");
}
}
const { handleChange, values, handleSubmit, errors } = useForm(
submitForm,
validate
);
useEffect(() => {
if (localStorage.getItem("user-info")) {
submitForm();
}
}, []);
const fetchLogin = async (email, password) => {
try {
setLoading(true);
const res = await Axios({
method: "POST",
url: `url`,
headers: {
},
data: {
user_email: email,
user_password: password,
},
});
if (res.status === 200) {
setLogin(true);
localStorage.setItem("user-info", JSON.stringify(res.data));
}
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
};
return (
<>
<div>
<div className="form-container">
<div className="form-content-left">
<img className="form-img" src={redtruck} alt="spaceship" />
</div>
<div className="form-content-right">
<h1>SIGN IN</h1>
<form className="form" onSubmit={handleSubmit}>
<div className="form-inputs">
<label htmlFor="email" className="form-label">
Email address
</label>
<input
id="signin-email"
type="email"
name="email"
placeholder="Enter email"
className="form-input"
value={values.email}
onChange={handleChange}
/>
{errors.email && <p>{errors.email}</p>}
</div>
<div className="form-inputs">
<label htmlFor="password" className="form-label">
Password
</label>
<input
id="signin-password"
type="password"
name="password"
placeholder="Password"
className="form-input"
value={values.password}
onChange={handleChange}
/>
{errors.password && <p>{errors.password}</p>}
{login ? "" : <p>The password or the email is wrong</p>}
</div>
<button
variant="primary"
type="submit"
className="form-input-btn"
>
LOGIN
</button>
</form>
</div>
</div>
</div>
</>
);
};
export default withRouter(Login);
So, my problem is even though the password or the email is wrong, it is still redirecting to '/admin'. So, I dont want it to redirect to the page '/admin' when the credentials are wrong but also I want to show error message if the password or email is wrong. If you could give me any suggestion on this, I will be really glad.
Thanks...
You should only use the onSubmit callback from the form.
At the moment, you are calling the handleSubmit and loginButton functions when the user clicks login. Remove the loginButton callback and execute your logic in the onSubmit callback from the form. Also be sure to event.preventDefault() at the beginning of the form callback.
If your button has type="submit", it will submit the form automatically.
The submitForm function should looks something like this:
async function submitForm() {
setIsSubmitted(true);
try {
await fetchLogin();
auth.login(() => {
history.push("/admin");
});
} catch (e) {
// User is not logged
}
}
And just throw in the fetchLogin function if the login fails
You should either use loginButton() or submitForm() to handle the login.
Use e.preventDefault() default like this to prevent auto submit. Use the Button Click to Submit the form.
You can use Button Click Event and Remove form submit.
<button
variant="primary"
type="submit"
className="form-input-btn"
onClick={handleLoginSubmit}
>
LOGIN
</button>
const handleLoginSubmit = async (event) => {
event.preventDefault();
setIsSubmitted(true);
try {
await fetchLogin(values.email, values.password);
auth.login(() => {
history.push("/admin");
});
} catch (e) {
console.log("wrong pass");
}
}

React: Why sign up form is not creating new user in firebase users?

Here I'm trying to build a signup form using the react-hook form. I'm trying to build a restaurant website for my own purpose. But I have tried many times. But I'm getting many errors. First of all when I sign up a new user then firebase is not creating a new user. The form is not validating completely. But I can't find out the problem. Where is the problem? Can anyone help, please?
Here is my signUp.js file
import React, { useEffect, useState } from 'react';
import { useAuth } from './useAuth'
import { useForm } from 'react-hook-form';
import logo from '../../Images/logo2.png';
import './SignUp.css'
const SignUp = () => {
const [returningUser, setReturningUser] = useState(false);
const {register, handleSubmit, watch, errors} = useForm();
const auth = useAuth();
const onSubmit = data => {
if(returningUser){
if(data.email && data.password){
auth.signIn(data.email, data.password)
}
}
else{
if(data.name && data.email && data.password){
auth.signUp(data.email, data.password, data.name)
}
}
}
return (
<div className="sign-up">
<div className="container">
<div className="logo-container ">
<img src={logo} alt=""/>
</div>
{
returningUser ?
<form onSubmit={handleSubmit(onSubmit) } action="" className="py-5">
{
auth && auth.user != null && <p className="text-danger">{auth.user.error}</p>
}
<div className="form-group">
<input name="email" className="form-control" {...register('email', {requried: true})} placeholder="Email"/>
{errors && errors.email && <span className="error">Email is Required</span>}
</div>
<div className="form-group">
<input type="password" name="password" className="form-control" {...register('password', {requried: true})} placeholder="password"/>
{errors&& errors.password && <span className="error">Password is Required</span>}
</div>
<div className="form-group">
<button className="btn btn-danger">Sign In</button>
</div>
<div className="option text-center">
<label onClick={() => setReturningUser(false)}>Create a new Account</label>
</div>
</form>
:
<form action="" onSubmit={handleSubmit(onSubmit)}>
<div className="form-group">
<input type="text" name="name" className="form-control"
{...register('name', {requried: true})} placeholder="Name"/>
{errors && errors.name && <span className="error">Name is Required</span>}
</div>
<div className="form-group">
<input type="email" name="email" className="form-control" {...register('email', {required: true})} placeholder="Email"/>
{errors && errors.email && <span className="error">Email is required</span>}
</div>
<div className="form-group">
<input type="password" name="password" className="form-control" {...register('password', {requried: true})} placeholder="Password"/>
{errors && errors.password && <span className="error">Password is Required</span>}
</div>
<div className="form-group">
<button className="btn btn-danger" type="submit">Sign Up</button>
</div>
<div className="option text-center">
<label onClick={() => setReturningUser(true)}>Already have an account!</label>
</div>
</form>
}
</div>
</div>
);
};
export default SignUp;
Here is my useAuth.js file
// import { faWindowRestore } from '#fortawesome/free-solid-svg-icons';
import firebase from "firebase/app";
import "firebase/auth";
import firebaseConfig from "../../firebase.config";
import { createContext, useContext, useEffect, useState } from "react";
import { Redirect, Route } from "react-router";
firebase.initializeApp(firebaseConfig);
const AuthContext = createContext();
export const AuthProvider = (props) => {
const auth = Auth();
return (
<AuthContext.Provider value={auth}>{props.children}</AuthContext.Provider>
);
};
export const useAuth = () => {
useContext(AuthContext);
};
export const PrivateRoute = ({ children, ...rest }) => {
let auth = useAuth();
return (
<Route
{...rest}
render={({ location }) =>
auth.user ? (
children
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location },
}}
/>
)
}
/>
);
};
const Auth = () => {
const [user, setUser] = useState(null);
useEffect(() => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const currentUser = user;
setUser(currentUser);
// ...
} else {
// User is signed out
// ...
}
});
}, []);
const signIn = (email, password) => {
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((res) => {
// Signed in
setUser(res.user);
window.history.back();
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
});
};
const signUp = (email, password, name) => {
return firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((res) => {
// firebase
// .auth()
// .currentUser.updateProfile({
// displayName: name,
// })
// .then(() => {
setUser(res.user);
window.history.back();
})
// Signed in
// ...
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ..
});
};
const signOut = () => {
return firebase
.auth()
.signOut()
.then((res) => {
// Sign-out successful.
setUser(null);
})
.catch((error) => {
// An error happened.
});
};
return {
user,
signIn,
signUp,
signOut,
};
};
export default Auth;

Resources