my data is not adding in to my firebase real time database - javascript

my data is not adding in to my firebase real time database. I have facing the problem during sending data in firebase real time database. It gives an error config_firebase__WEBPACK_IMPORTED_MODULE_0_.default.database is not a function.
I also import 'firebase/database' in my firebase.js file.
import firebase from "../../config/firebase"
import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth";
const facebook_login=()=>{
return (dispatch)=>{
const provider = new FacebookAuthProvider();
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
console.log("Facebook Login")
var user = result.user;
var credential = FacebookAuthProvider.credentialFromResult(result);
var accessToken = credential.accessToken;
let create_user={
name:user.displayName,
email:user.email,
profile:user.photoURL,
uid:user.uid
}
firebase.database().ref('/').child(`users/${user.uid}`).set(create_user)
.then(()=>{
alert("Login Successfull")
})
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = FacebookAuthProvider.credentialFromError(error);
console.log(errorMessage)
});
}
}
export{
facebook_login
}

Since you are using the new Modular SDK, you should not use the firebase.database() namespaced syntax.
import { getDatabase, ref, set } from "firebase/database";
const db = getDatabase();
set(ref(db, `users/${user.uid}`), create_user);
You can learn more about the modular syntax in the documentation.

Related

Cannot POST Sign In Result from Firebase

Hey all so I'll keep it short. I've used firebase to log users in and recently implemented 'Sign In with Apple'. The following code is able to open the pop up and let users sign in with their Apple ID but the moment they hit sign in my web app remains unaffected and the console shows the following error:
The script that I'm using is following:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.1/firebase-app.js";
import { getAuth ,OAuthProvider, signInWithRedirect, getRedirectResult, signInWithPopup, signOut } from "https://www.gstatic.com/firebasejs/9.4.1/firebase-auth.js";
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const provider = new OAuthProvider('apple.com');
provider.addScope('email');
provider.addScope('name');
signInWithPopup(auth, provider)
.then((result) => {
// The signed-in user info.
const user = result.user;
// Apple credential
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
const idToken = credential.idToken;
// ...
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The credential that was used.
const credential = OAuthProvider.credentialFromError(error);
// ...
});
getRedirectResult(auth)
.then((result) => {
const credential = OAuthProvider.credentialFromResult(result);
if (credential) {
// You can also get the Apple OAuth Access and ID Tokens.
const accessToken = credential.accessToken;
const idToken = credential.idToken;
}
// The signed-in user info.
const user = result.user;
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The credential that was used.
const credential = OAuthProvider.credentialFromError(error);
// ...
});
When I click the 'index.ts:116' link I get the error at the following line:
Any input shall be appreciated. Please let me know if I can provide more information. Thanks!

I can create firebase user using this code, but how can I add display Name, phone Number and other information in default firebase user table? Thanks

This is my funcation code.
const signUpFun = () => {
if (isValidForm()) {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
setbitdata({});
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
setEmailAndPasswordCheck(true)
setTimeout(() => {
setEmailAndPasswordCheck(false)
}, 3500)
});
}
}
import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
updateProfile(auth.currentUser, {
displayName: "My Name", photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
// Profile updated!
}).catch((error) => {
// An error occurred
});
If you are using firebase version 8, then you should use like these:
import firebase from "firebase";
const user = firebase.auth().currentUser;
user.updateProfile({
displayName: "My Name",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
// Update successful
}).catch((error) => {
// An error occurred
});
Firebase have very great documentation, you should probably read that, as like #Alexandros Giotas mentioned the link for official Documentation for your question
You're probably looking for the updateProfile method.
Using modular imports:
import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
updateProfile(auth.currentUser, {
displayName: "Your display name here",
// more updating..
}).then(() => {
// Success
}).catch((e) => {
// Handle errors.
});
Remember that updateProfile returns a Promise which you should handle, with either then() & catch() as shown above or await if you're updating within an async function.
I encourage you to read the Firebase docs on updating a user's profile.
There are more code snippets there, that answer your question probably better than I did.

Firebase SignInWIthEmailAndPasswod doesn't work

I'm having issues implementing Login logic using Firebase email and password method. I've done everything according to documentation for 8 and 9 SDK versions but they don't work. To be more specific .then doesn't work.
I've implemented register and sign out without any issue, but login doesn't do anything. Here is login:
import firebase from 'firebase/app'
import 'firebase/auth';
import { useHistory } from 'react-router-dom';
...
const loginUser = (email, password) => {
firebase.auth().signInWithEmailAndPassword(email, password).then((userCredential) => {
console.log('user', userCredential)
history.push('/admin')
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.error(errorCode, errorMessage)
});
}
}
...
Whatever I try to log in .then() nothing happens, there is also no error. In network tab verifyPassword request is cancelled.
I really don't understand what is wrong there since it should be easy implementation.
Thanks
firebase.auth()
is not available in Firebase V9. Make sure to read Docs of Firebase V9.
Because Firebase V9 doesn't built-in Object-Oriented Way. It was built with Functional
Way.
You can change as
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';
const firebaseConfig = {
////
}
initializeApp(firebaseConfig)
const auth = getAuth()
const loginUser = (email, password) => {
signInWithEmailAndPassword(auth, email, password).then((userCredential) => {
console.log('user', userCredential)
history.push('/admin')
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.error(errorCode, errorMessage)
});
}
}
Kindly read the Documentation to your doubts.
I would recommend you to watch Net Ninja's Firebase V9
Click here

How to export async var from a login

I am trying to export user info from login to other modules.
export function login(){
console.log("entrando A LOGIN")
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth()
.signInWithPopup(provider)
.then((result) => {
/** #type {firebase.auth.OAuthCredential} */
var credential = result.credential;
var token = credential.accessToken;
// The signed-in user info.
let user = result.user;
module.exports.user=user /// it says it does not provide user variable when in this ine I am
doing it
}etc....
/// it says it does not provide user variable but I do it.Thanks I am new
You don't need to use module.exports at all as far as I know. And you really don't want to mix them with es6 modules.
// google-auth.js
export function login() {
const provider = new firebase.auth.GoogleAuthProvider();
return firebase.auth()
.signInWithPopup(provider)
.then((result) => {
const credential = result.credential;
const token = credential.accessToken;
const user = result.user;
return user;
})
.catch(error => {
// you deal with errors that happen here
})
}
You get the user object by returning it from the function. The function returns a promise though so, if you try and do something like const user = login() it's not going to work To import the function into another file and use it in a way that you can access the user object, you'd do something like this:
// login.js
import { login } from './path/to/google-auth.js'
const authInstance = login();
From the official docs:
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// ...
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});

Firebase Firestore db.collection is not a function

I am developing a shift scheduler and I use firebase authentication and firestore. My idea is that when a user signs up it creates a document in collection "workers" and sets the doc id to the user's email. When the user adds a shift I want to add the shift info into a sub-collection "shifts" inside that user's document where all the shifts will be stored. I have read and seen many guides but I can't get the syntax/logic right, and due to firebase changes of syntax I am including most of the settings I use.
firebase.js:
import { getAuth } from "firebase/auth";
import "firebase/firestore";
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore"
require('firebase/auth');
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth(app);
export default app
SignUp.js:
import { db } from "../firebase";
import { collection, addDoc, setDoc, doc } from "firebase/firestore";
import { useAuth } from '../contexts/AuthContext';
const { signup } = useAuth();
const handleSubmit = async (event) => {
event.preventDefault();
setError("");
try{
const data = new FormData(event.currentTarget);
await signup ( data.get('email'), data.get('password'));
const docRef = await setDoc(doc(db, "workers", data.get('email')), {
firstName: data.get('firstName'),
lastName: data.get('lastName'),
email: data.get('email'),
numberOfShifts: 0
});
}
catch(e){
console.error("Error adding document: ", e);
setError("Failed to create an account");
};
The sign up works nicely and the document id is the email. The error is when I try to add shift to that document (the collection shifts is not created at this stage)
Datasheed.js: (where the user inputs their shifts)
import { auth } from "../firebase"
import { db } from "../firebase";
const commitChanges = async ({ added, changed, deleted }) => {
if (added) {
try {
db.collection("workers")
.doc(auth.currentUser.email)
.collection("shifts")
.add(added);
} catch (e) {
console.error("Error adding document: ", e);
}
}
For now I am only trying to add, and the caught exception I am getting is:
Error adding document: TypeError: firebase__WEBPACK_IMPORTED_MODULE_5_.db.collection is not a function.
From what I have read the problem is that I use firebase modular and it doesn't have db.collection anymore and it uses collection refs. Do I need the collection ref for the sub-collection as well? What changes do I need to do in order to implement this?
You are using Modular SDK and also modular syntax in signup.js. You should use the same syntax everywhere else. Try refactoring like this:
const commitChanges = async ({ added, changed, deleted }) => {
if (added) {
try {
await addDoc(collection(db, "workers", auth.currentUser.email, "shifts"), added)
} catch (e) {
console.error("Error adding document: ", e);
}
}
}
You can learn more about the new syntax in the documentation.

Categories