base.jsx:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
config
};
export const app = initializeApp(firebaseConfig);
export const auth = getAuth();
Register.jsx
import React, { useState } from "react";
import { auth } from "../components/base";
import { Link, useNavigate } from "react-router-dom";
function Register() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(null);
let navigate = useNavigate();
const handleRegister = async (e) => {
e.preventDefault();
try {
await auth.createUserWithEmailAndPassword(email, password);
await auth.signInWithEmailAndPassword(email, password);
navigate("/");
} catch (error) {
setError(error.message);
}
};
return (
<div className="register">
<div className="container">
<div className="box">
<form onSubmit={handleRegister}>
<h2>Register</h2>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Enter email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Register
</button>
<div>{error && <p className="error">{error}</p>}</div>
</form>
<p className="sign-up">
Already have an account?
<Link to="/login">
<span>Login</span>
</Link>
</p>
</div>
</div>
</div>
);
}
export default Register;
It's pretty much self explanatory, can you guys please help me fix this issue? I've been struggling for 2 hours.
I want createUserWithEmailAndPassword to work in Register.jsx so I can later on sign in Login.jsx with the same information. However on the website when I click the submit button in Register.jsx, auth.createUserWithEmailAndPassword is not a function pops out
You're using the v9 SDK version, which uses a modular API with top-level functions. So createUserWithEmailAndPassword
is not longer a method on the auth
object, but is now a top-level function that you have to import similar to what you do for getAuth
and to which you then pass the auth
object as its first parameter:
createUserWithEmailAndPassword(auth, "username", "password")
When you are programming this new API or getting errors otherwise, I recommend keeping the documentation handy. In this case you can see code similar to what you're trying and what I have above in the documentation on creating a user. Also have a look at the blog post introducing the modular SDK, and the upgrade guide.