I make this post because I had a problem when making a registration form using React Hooks + Firebase,
The problem is that whatever you touch is automatically sent to the database,
Here is the registration form:
import React, { useState } from 'react'
import '../css/login-register/login.css'
import firebase from "../firebase";
import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth'
const Register = (e) => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const miSubmit = () => {
const auth = getAuth()
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log('Registrado')
const user = userCredential.user
// ...
})
.catch((error) => {
const errorCode = error.code
const errorMessage = error.message
console.log('error: ' + errorMessage + 'Error code ' + errorCode)
})
e.preventDefault();
console.log('Ejecutando submit sin evento');
}
return (
<div>
<form action="" onSubmit={miSubmit}>
<input type="text"
id="email"
placeholder="Email"
onChange={(e) => setEmail(e.target.value)}/>
<input type="password"
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}/>
<input className="waves-effect waves-light btn" type='submit' name="Register" value='registro' />
</form>
</div>
)
}
export default Register
multiple problems.
onSubmit
reference to the same componentRegister
which should not be so.createUserWithEmailAndPassword
directly inside the component, which causes it to always run when you usesetEmail
orsetPassword
.onSubmit
will never execute if thoseinput
are not inside yourform
, especially yourinput
of typesubmit
To see at a glance the problem caused by
setEmail
orsetPassword
let's place aconsole.log()
inside the component to see how it is printed and executed every time we write in theinput
This only as an example and show what happens every time you write and why your problem
Solution to the problem
Problem 1 and 2
To solve your problem, we must create a method that will be executed only when it is the submit and place it in the
onSubmit
problem 3
You
form
should contain the onesinput
you will control or need, including thesubmit
.Your code should generally look something like this.
Avoid page reload when using
submit
for this we only receive the event and use
e.preventDefault()
example