The function createUserWithEmailAndPassword is not being called within SignUpUser function when onClick event happening. But when I do onClick={signUpUser(email,password)} it works
import React from 'react';
import styled from 'styled-components';
import { useState } from 'react';
import { signUpUser } from '../firebase';
function SignUpComponent() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
return (
<AuthForm>
<input type="text"
placeholder="Email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}/>
<input type="password"
name="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}/>
<SubmitFormButton
type="submit"
onClick={() => signUpUser(email,password)}
>
Sign Up
</SubmitFormButton>
</AuthForm>
)
};
Here is my firebase.js file
import { initializeApp } from "firebase/app";
import {
getAuth,
onAuthStateChanged,
signInWithPopup,
signOut,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
} from 'firebase/auth';
const firebaseConfig = {
apiKey: ****,
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth();
auth.useDeviceLanguage();
// Auth functions
export function signUpUser(email, password) {
if (password.length < 6) {
alert('Password is too short');
return;
};
˚˚createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
alert('Signed up Successfully', user);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
});
};
onClick={signUpUser(email,password)}
Here the signUpUser is called during a render, no matter if clicked or not.
If it works that way and does not work with
onClick={() => signUpUser(email,password)}
then there are no other options but your SubmitFormButton does not trigger onClick. Maybe it is not passed to the DOM at all.
The problem is that the Auth form should implement "onSubmit" method. We should not call the function on the SubmitFormButton component
Related
The login.js is where the "Cannot read properties of undefined (reading 'auth')" coming from I would guess
Login.js:
import { useContext, useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import FirebaseContext from "../context/firebase";
import * as ROUTES from "../constants/routes";
export default function Login() {
const navigate = useNavigate();
const { firebase } = useContext(FirebaseContext);
const [emailAddress, setEmailAddress] = useState(" ");
const [password, setPassword] = useState(" ");
const [error, setError] = useState(" ");
const isInvalid = password === "" || emailAddress === "";
const handleLogin = async (event) => {
event.preventDefault();
try {
await firebase.auth().signInWithEmailAndPassword(emailAddress, password);
navigate.push(ROUTES.HOMEPAGE);
} catch (error) {
setEmailAddress(" ");
setPassword(" ");
setError(error.message);
}
};
useEffect(() => {
document.title = "Login - Bits&Bots";
}, []);
return (
<div className="login__container">
<div className="loginform">
<p>I will be the form</p>
{error && <p classname="error-text">{error}</p>}
<form onSubmit={handleLogin} method="POST">
<input
aria-label="Enter your email addres"
type="text"
placeholder="Email address"
classname="login__input"
onChange={({ target }) => setEmailAddress(target.value)}
/>
<input
aria-label="Enter your password"
type="password"
placeholder="Password"
classname="login__input"
onChange={({ target }) => setPassword(target.value)}
/>
<button disabled={isInvalid} type="submit" classname="login__submit">
Log in
</button>
</form>
</div>
<div className="create__account">
<p>
Don't have an account?{``}
<Link to="/signup" className="signup__link">
Sign up
</Link>
</p>
</div>
</div>
);
}
so there is a "import FirebaseContext from "../context/firebase";" in this file.
What contains inside that firebase.js file is:
import { createContext } from "react";
const FirebaseContext = createContext(null);
export default FirebaseContext;
So I cant seem to understand why the text "Cannot read properties of undefined (reading 'auth')" appearing when typing inside the form.
Here is a image of it:
If more detailed needed, here is the index.js file:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import FirebaseContext from "./context/firebase";
import { db, analytics, FieldValue, auth } from "./lib/firebase";
ReactDOM.render(
<FirebaseContext.Provider value={{ db, analytics, FieldValue, auth }}>
<App />
</FirebaseContext.Provider>,
document.getElementById("root")
);
and different firebase.js file from /lib
import firebase from "firebase/compat/app";
import "firebase/compat/firestore";
import "firebase/compat/analytics";
import "firebase/compat/auth";
// // here i want to import the seed file
// import { seedDatabase } from "../seed";
const firebaseConfig = {
apiKey: "0",
authDomain: "0",
projectId: "0",
storageBucket: "0",
messagingSenderId: "",
appId: "0",
measurementId: "0",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const analytics = firebaseApp.analytics();
const auth = firebase.auth();
const FieldValue = db.FieldValue;
console.log(db);
// seedDatabase(db, "db");
export { db, analytics, FieldValue, auth };
I will apprechiate all the help i can get.
I'd suggest you read up on the differences between firebase v8 and v9, some of the instantiation of the firebase functions there is of v8 while some v9. I haven't used firebase for that long but in v9, a simple auth instantiation would look like this:
firebase.js
import { initializeApp } from 'firebase/app';
const firebaseConfig = {
apiKey: "0",
authDomain: "0",
projectId: "0",
storageBucket: "0",
messagingSenderId: "",
appId: "0",
measurementId: "0",
};
export default const firebaseApp = initializeApp(firebaseConfig);
And in another file e.g. login.js
import Firebase from "../Firebase";
import {getAuth, signInWithEmailAndPassword} from "firebase/auth"
var auth = getAuth(Firebase);
//more code over here
const mainFunc = () => {
//more code here
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
}
I know the compat library is there to offer backward compatibility to v8 but unless your project is super huge or something, I'd recommend you use the v9 way of doing things. It's cleaner.
heres a link to the firebase docs : https://firebase.google.com/docs/web/modular-upgrade
Regards.
I'm trying to signup using the firebase - createUserWithEmailAndPassword method, but it returns undefined when I try to log the returned value.
My config file :
import firebase from "firebase/app"
import "firebase/auth"
import "firebase/firestore"
const firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxx",
projectId: "xxxxxx",
storageBucket: "xxxxxx",
messagingSenderId: "xxxxxx",
appId: "xxxxxxx",
}
firebase?.initializeApp(firebaseConfig)
const auth = firebase?.auth()
const firestore = firebase?.firestore()
export { auth, firestore }
My signup file:
import React, { useState } from "react"
import { auth } from "../firebase"
function Signup(props: Props) {
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
console.log({ email, password })
async function handleSubmit(e) {
console.log("clicked")
e.preventDefault()
const res = await auth?.createUserWithEmailAndPassword(email, password)
console.log(res) -> gives undefined
}
return (
<>
<div>
<form onSubmit={(e) => handleSubmit(e)}>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<input value={password} onChange={(e) => setPassword(e.target.value)} />
<button type='submit'>Submit</button>
</form>
</div>
</>
)
}
export default Signup
I'm using firebase version - 9.6.5
On the Firebase dashboard, I don't see anything getting logged neither I get any error on the console.
I have already read other such answers the solution is mostly around using the right package version/upgrading, deleting node modules or initializing the config carefully. I believe I'm doing these steps right.
I'm not sure what I'm doing wrong, any help in the right direction would be very helpful. thanks!
https://firebase.google.com/docs/auth/web/password-auth#web-version-9
Please check the official Doc for v9.
I think your approach corresponds to v8
I am using same approach as yours for v8 and its working Good.
Or you can try to deprecate to v8 and try your code on that.
I've figured out the issue here, v9 documentation changes how we import and use the method,
In the config file,
import { initializeApp } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
const firebaseConfig = {
....
}
// Initialize Firebase
initializeApp(firebaseConfig)
const db = getFirestore()
const auth = getAuth()
export { auth, db }
import { auth } from "../firebase"
import { createUserWithEmailAndPassword } from "firebase/auth"
createUserWithEmailAndPassword(auth, email, password).then((i) => console.log(i))
I am struggling now with this question for couple of days. Can somebody provide precise solution based on my code. Please do not refer mi on firebase documentation because it is very unclear. I am not familiar with firebase. In my code I know the problem is somewhere in handleReg method. Curentlly, my user is being created. However, no data is writen in my firebase db collection. I need to achieve to have same doc id(uid) for the new users and his aditional data that i want to store in firebase db collection. Please somebody provide precise solution. It is very frustrating that Firebase documentation does not provide a clear explanation on how to do it. Also I check all stack overflow links. They are not offering solution to this question. Pleas Help
import React, {useState} from "react";
import { View, Button } from "react-native";
import { TextInput } from "react-native-paper";
import { doc, setDoc, collection, addDoc } from "firebase/firestore";
import { db } from "../firebase/firebase.authentication";
import { auth } from "../firebase/firebase.authentication";
import { createUserWithEmailAndPassword} from "firebase/auth";
export const RegisterScreen = () => {
const [email, setEmail] = useState("");
const [password, setpassword] = useState("");
const HandleReg = () => {
createUserWithEmailAndPassword(auth, email, password)
.then(registredUser => {
const {uid}= registredUser.user.uid
const SetData = async ()=>{
await setDoc(doc(db, "user", uid),{
name:"test"
})
}
})
}
return (
<>
<View>
<TextInput value={email}
onChangeText={(text)=> setEmail(text)}
/>
<TextInput
value={password}
onChangeText={(text)=> setpassword(text)}
/>
<Button title="set" onPress={HandleReg}/>
</View>
</>
);
}
And My Firebase js :
import {initializeApp} from "firebase/app"
import { getAuth} from "firebase/auth";
import {getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "xx",
authDomain: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const db = getFirestore(app);
When it the SetData function being called? Try refactoring the function as shown below:
const HandleReg = async () => {
const { user } = await createUserWithEmailAndPassword(auth, email, password)
await setDoc(doc(db, "user", user.uid), { name:"test" })
console.log('Document Added')
}
I was using Firebase over year ago and I am confused on how to do basic CRUD in newest Firebase.
My Todo item that I want to add to Firebase db is:
import React, { useState } from 'react';
import firebase from '../utils/firebase'
export default function Form() {
const [title, setTitle] = useState('')
const handleChange = (e) => {
setTitle(e.target.value)
}
const createTodo = () => {
const todoRef = firebase.database().ref('Todo')
const todo = {
title,
complete: false
};
todoRef.push(todo)
}
return (
<div>
<input type="text" onChange={handleChange} value={title}/>
<button onClick={createTodo}>Add Todo</button>
</div>
)
}
My firebase.js in utils is:
import firebase from 'firebase/compat/app';
const firebaseConfig = {
apiKey: "AIzaSyDyfhIiB32tReM7E66wFR8oD0mMC3LKZWM",
authDomain: "nutriapp-b77ee.firebaseapp.com",
projectId: "nutriapp-b77ee",
storageBucket: "nutriapp-b77ee.appspot.com",
messagingSenderId: "717648627918",
appId: "1:717648627918:web:b382565fc790dd1495a89f",
measurementId: "G-W3H2K8NGNJ"
};
firebase.initializeApp(firebaseConfig)
export default firebase;
Please help, thanks
its giving me the error cant figure it out i think its related to the firebase.js but same configuration working in other project fine but this one has that issue.
import React, { useState } from 'react';
import uuid from 'react-uuid';
import { useSelector, useDispatch } from 'react-redux';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import database from '../firebase/firebase';
const AddTasks = () => {
const dispatch = useDispatch();
const newLocal = null;
const [selectedDate, setSelectedDate] = useState(newLocal);
const [task, setTask] = useState('');
const date = new Date()
const userId = useSelector(state => state.auth.currentUser);
const addTask = () => {
const payload = { id: uuid(), text: task, completed: false, addedAt: selectedDate.toString() }
here its giving me that error i will also share my firebase.js after this
const dbtasksWrapper = database.ref().child(userId).child('tasks');
return dbtasksWrapper.child(payload.id).update(payload).then(() => {
setTask('');
setSelectedDate(null);
dispatch({ type: "ADD_TASKS", payload })
})
}
return (
<form onSubmit={e => {
e.preventDefault(e.target.value);
addTask();
}}>
<input className="input-group-prepend"
value={task}
placeholder="Enter your Task"
onChange={e => setTask(e.target.value)}
/>
<DatePicker className="input-group-prepend" placeholderText="Enter task date " selected={selectedDate} onChange={(date) => setSelectedDate(date)} showTimeSelect timeFormat="HH:mm" timeIntervals={15} timeCaption="time" dateFormat="MMMM d, yyyy H:mm aa" minDate={date} /><br />
<input className="btn btn-primary" type='submit' value='Submit' />
</form>
);
};
export default AddTasks;
here is my firebase.js file dont know how to get rid of this issue
import app from 'firebase/app';
import 'firebase/auth';
import "firebase/firestore";
import "firebase/database"
var firebaseConfig = {
apiKey: "AIzaSyAM7bXNJc-BlyLjUK23laYxDXSdqrg5m0A",
authDomain: "hse-project-aefd3.firebaseapp.com",
databaseURL: "https://hse-project-aefd3-default-rtdb.firebaseio.com",
projectId: "hse-project-aefd3",
storageBucket: "hse-project-aefd3.appspot.com",
messagingSenderId: "651568614628",
appId: "1:651568614628:web:2d0e91e352bbe6ef6970f1"
};
const firebase = app.initializeApp(firebaseConfig);
// Get a reference to the database service
export const database = firebase.database();
export default firebase;
There is no exported module "app" in "firebase/app"
You should import firebase from 'firebase/app'
import firebase from 'firebase/app';
import 'firebase/auth';
import "firebase/firestore";
import "firebase/database"
var firebaseConfig = {
apiKey: "AIzaSyAM7bXNJc-BlyLjUK23laYxDXSdqrg5m0A",
authDomain: "hse-project-aefd3.firebaseapp.com",
databaseURL: "https://hse-project-aefd3-default-rtdb.firebaseio.com",
projectId: "hse-project-aefd3",
storageBucket: "hse-project-aefd3.appspot.com",
messagingSenderId: "651568614628",
appId: "1:651568614628:web:2d0e91e352bbe6ef6970f1"
};
const app = firebase.initializeApp(firebaseConfig);
// Get a reference to the database service
export const database = app.database();
export default firebase;