Firebase v9 auth.currentUser is null after creating the user - javascript

Here's my JS code:
import { ref } from "vue"
import { projectAuth } from '../firebase/config'
import { getAuth, createUserWithEmailAndPassword, updateProfile } from 'firebase/auth'
const error = ref(null)
const isPending = ref(false)
const signup = async(email, password, displayName) => {
error.value = null
isPending.value = true
try {
const res = createUserWithEmailAndPassword(projectAuth, email, password)
console.log(projectAuth.currentUser)
if (!res) {
console.log('Could not complete the signup')
throw new Error('Could not complete the signup')
}
console.log(projectAuth.currentUser)
await updateProfile(projectAuth.currentUser, {displayName})
error.value = null
isPending.value = false
return res
} catch(err) {
console.log('ERROR: ' + err.message)
error.value = err.message
isPending.value = false
}
}
const useSignup = () => {
return {error, signup, isPending}
}
export default useSignup
My Vue3 application is calling the signup function in this script whenever a user is signing up. The createUserWithEmailAndPassword function is successful and the user shows up in firebase. But I want to also add a display name to my user, so I'm trying to use the updateProfile function to do that but there's a problem.
The problem is the projectAuth.currentUser is null even after creating the user and I can't figure out why??

The createUserWithEmailAndPassword() method returns a promise. Since your function is async, try adding await:
const res = await createUserWithEmailAndPassword(projectAuth, email, password)
console.log(projectAuth.currentUser)
Alternatively, you can pass User object to updateProfile directly from res:
const { user } = await createUserWithEmailAndPassword(projectAuth, email, password)
await updateProfile(user, { displayName })

Related

Firebase JS db._checkNotDeleted is not a function

I'm writing a program that needs to add JSON data to my realtime firebase database, however I keep getting TypeError: db._checkNotDeleted is not a function at the ref() statement.
const { firebaseConfig } = require("./key");
const { EMAIL, PASSWORD } = require("./login");
const { initializeApp } = require("firebase/app");
const { getAuth, signInWithEmailAndPassword } = require("firebase/auth");
const { getDatabase, ref, update } = require("firebase/database");
async function setupFirebase(firebaseConfig, email, password) {
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
try {
await signInWithEmailAndPassword(auth, email, password);
} catch (e) {
console.error(e.message);
}
return getDatabase(app);
}
const db = setupFirebase(firebaseConfig, EMAIL, PASSWORD);
try {
const jsonData = require("foldername/filename");
update(ref(db, "machines/" + jsonData.MachineID), {
timestamp: jsonData.DateTimeMessage,
status: jsonData.Status,
});
} catch (e) {
console.error(e);
}
I have already tried to use set() or split my update to mimic the firebase docs as closely as possible but without any success. The problem seems to originate from the ref() statement itself as I cannot seem to use it in any way.

I am making a project to add users in MongoDB but I am getting ERR_HTTP_HEADERS_SENT

import axios from 'axios';
// const usersUrl = 'http://localhost:3003/users';
const usersUrl = 'http://localhost:8020/users';
export const getUsers = async (id) => {
id = id || '';
return await axios.get(`${usersUrl}/${id}`);
}
export const addUser = async (user) => {
return await axios.post(`${usersUrl}/add`, user);
}
export const deleteUser = async (id) => {
return await axios.delete(`${usersUrl}/${id}`);
}
export const editUser = async (id, user) => {
return await axios.put(`${usersUrl}/${id}`, user)
}
This my client code when I try to add user it adds the user and details in back end in mongo db but cant view it in the front end when I click on the specific user.
import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";
const usersUrl = 'http://localhost:8020/users';
const View = () => {
const [user, setUser] = useState({
projectname: '',
projecttype: '',
numberofissuesreported: '',
retestlead: '',
progress: '',
startdate: '',
enddate: '',
});
const { id } = useParams();
useEffect(() => {
loadUser();
//getUsers();
}, []);
const loadUser = async () => {
const res = await axios.get(`http://localhost:8020/users/add`);
setUser(res.data);
};
And this is my view.jsx file.
As the error mentions clearly, if you use response.send, it sends the data to the client. You cannot modify the states once they are sent.
Corrected Code:
export const addUser = async (request, response) => {
// retreive the info of user from frontend
const user = request.body;
// Removed the line
const newUser = new User(user);
try{
await newUser.save();
response.status(201).json(newUser);
} catch (error){
return response.status(404).json({ message: error.message});
}
}
Tip: If you are debugging, just use console.log instead of response.send and see those values on the terminal.
Example:
export const addUser = async (request, response) => {
// retreive the info of user from frontend
const user = request.body;
console.log("Executing..");
console.log(user);
const newUser = new User(user);
try{
await newUser.save();
response.status(201).json(newUser);
} catch (error){
return response.status(404).json({ message: error.message});
}
}

(Firebase Firestore)TypeError: n.indexOf is not a function

I'm trying to add another field value in a document but firebase returns TypeError: n.indexOf is not a function. Here's the code:
async function linkLCSN(cor, sn) {
try {
await setDoc(doc(db, "cor", cor), {
sn: sn,
}, {merge: true});
} catch(e) {
console.error(e);
}
}
I've already succeeded in doing this way but I don't know why this time it keeps giving me this error. This is the working code:
async function submitToDatabase(name, email, cor, cs, cn, concern) {
try {
//Set Datas
await setDoc(doc(db, "cor", cor), {
name: name,
email: email,
cor: cor,
courseSection: cs,
contactNumber: cn,
isViewed: false,
timestamp: serverTimestamp(),
}, {merge: true});
const docRef = await addDoc(collection(db, "cor", cor, "concerns"), {
concernData: concern,
});
console.log("Yung betlog nasa:" + docRef.id);
//Do page changes
let a = document.querySelector(".concern-main-container");
let b = document.querySelector(".concern-preview-container");
a.style.display = "none";
b.style.display = "block";
} catch(e) {
console.error(e);
//Custom Alert
}
}
I solved my problem by checking every type of params that passing to doc(), that params should not be Integer. It must be String
I'm assuming you are using v9 of firebase (modular version). It may sound silly, but make sure that you have initialized your app and that you are using a valid reference to a collection.
For example:
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const config = {/** your firebase config properties **/};
const app = initializeApp(config);
const db = getFirestore(app);
Then to add a new document, you can do:
const createDocument = (collectionName, document) => {
const colRef = collection(db, collectionName);
return addDoc(colRef, document);
};
Remember the addDoc function returns a promise, so be sure to handle this is the caller of createDocument

error with reauthenticateWithCredential get error TypeError: credential._getReauthenticationResolver is not a function (firebase 9)

I am learning firebase. now want to change password with reauthenticateWithCredential(). but get error like this.
TypeError: credential._getReauthenticationResolver is not a function
this the code:
import { getAuth, reauthenticateWithCredential, signInWithEmailAndPassword } from "firebase/auth";
const auth = getAuth();
const user = auth.currentUser;
const credential = signInWithEmailAndPassword(auth, user.email, this.oldPassword);
reauthenticateWithCredential(user, credential).then(() => {
// User re-authenticated.
console.log(credential)
}).catch((error) => {
console.log(error)
});
can anyone point out where the error is?
Maybe still not quite right, but give this a try :
import {
getAuth,
reauthenticateWithCredential,
EmailAuthProvider,
} from "firebase/auth";
const auth = getAuth();
const user = auth.currentUser;
try {
const credential = EmailAuthProvider.credential(
user.email,
this.oldPassword
);
reauthenticateWithCredential(user, credential).then(() => {
// User re-authenticated.
// Code...
});
} catch (error) {
console.log(error.message);
}

VUE firebase Making UI elements contingent on logged in state? Works when logged in, throws error when logging out

Hi I am trying to have a logged in state that has elements that are based on which user is logged in.
I get the user from firebase auth and then use the uid to check firestore for their data. This all works on the login however when I logout it throws the below error.
export default {
setup() {
const { user } = getUser();
if (user) {
const { error, document } = getDocument("collection", user.value.uid);
console.log(document);
return { document };
}}}
HTML
{{ document.gender }}
Error Received:
Profile.vue?49d8:13 Uncaught (in promise) TypeError: Cannot read
property 'uid' of null
at setup (Profile.vue?49d8:13)
at callWithErrorHandling (runtime-core.esm-bundler.js?5c40:154)
at setupStatefulComponent (runtime-core.esm-bundler.js?5c40:6542)
at setupComponent (runtime-core.esm-bundler.js?5c40:6503)
at mountComponent (runtime-core.esm-bundler.js?5c40:4206)
at processComponent (runtime-core.esm-bundler.js?5c40:4182)
at patch (runtime-core.esm-bundler.js?5c40:3791)
at componentEffect (runtime-core.esm-bundler.js?5c40:4298)
at reactiveEffect (reactivity.esm-bundler.js?a1e9:42)
at effect (reactivity.esm-bundler.js?a1e9:17)
getUser function
import { ref } from 'vue'
import { projectAuth } from '../firebase/config'
// refs
const user = ref(projectAuth.currentUser)
// auth changes
projectAuth.onAuthStateChanged(_user => {
console.log('User state change. Current user is:', _user)
user.value = _user
});
const getUser = () => {
return { user }
}
export default getUser
Get Document function
import { watchEffect, ref } from 'vue'
import { projectFirestore } from '../firebase/config'
const getDocument = (collection, id) => {
let document = ref(null)
let error = ref(null)
// register the firestore collection reference
let documentRef = projectFirestore.collection(collection).doc(id)
const unsub = documentRef.onSnapshot(doc => {
// need to make sure the doc exists & has data
if(doc.data()) {
document.value = {...doc.data(), id: doc.id}
error.value = null
}
else {
error.value = 'that document does not exist'
}
}, err => {
console.log(err.message)
error.value = 'problem fetching the document'
})
watchEffect((onInvalidate) => {
onInvalidate(() => unsub())
});
return { error, document }
}
export default getDocument

Categories