I got an error "_config.firebase.auth is not a function. (In '_config.firebase.auth()','_config.firebase.auth' is undefined)
This error appears when submitting a registration form.
I run Firebase version 9.6.5
Can anyone spot where I went wrong in my config.js and RegScreen.js files?
import firebase from 'firebase/compat/app';
import '#firebase/auth';
import '#firebase/firestore';
const firebaseConfig = {
apiKey: '',
authDomain: 'to-do-weather.firebaseapp.com',
databaseURL: 'https://DATABASE_NAME.firebaseio.com',
projectId: 'to-do-weather',
storageBucket: 'to-do-weather.appspot.com',
messagingSenderId: '',
appId: '',
};
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig)
} else {
app = firebase.app();
}
export { firebase };
const onRegPress = () => {
if (password !== confirmPassword) {
alert("Passwords don't match.")
return
}
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((response) => {
const uid = response.user.uid
const data = {
id: uid,
email,
fullName,
};
const usersRef = firebase.firestore().collection('users')
usersRef
.doc(uid)
.set(data)
.then(() => {
navigation.navigate('Home', {user: data})
})
.catch((error) => {
alert(error)
});
})
.catch((error) => {
alert(error)
});
}
If you are trying to use namespaced syntax then you must import compat versions of all Firebase services too. Try changing your imports to:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
// add /compat ^
The compat version would be removed eventually so I would recommend updating your code and following the new syntax as mentioned in the documentation
Related
so this is my first project with firebase and im trying to send data to database but the function is not working:
const onSignUp = async (email, password, username) => {
try {
const authUser = await createUserWithEmailAndPassword(
firebase,
email,
password
);
db.collection("users").add({
owner_uid: authUser.user.uid,
usernames: username,
email: authUser.user.email,
profile_pic: await randomProfiles()
})
.then(() => {
console.log("CREATED");
this.props.phase(0);
})
.catch(() => {
console.log("ERROR");
alert("Bruh");
});
} catch (error) {}
};
const randomProfiles = async () => {
const respone = await fetch("https://randomuser.me/api");
const data = await respone.json();
return data.results[0].picture.large;
};
I think the problem might be in
db.collection("users").add({
THIS IS THE EDITED PART NEW CODE:
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDVy_vUuhZN-qwMmTOUjsViQ4gW36q-Xxk",
authDomain: "social-media-app-d29f2.firebaseapp.com",
projectId: "social-media-app-d29f2",
storageBucket: "social-media-app-d29f2.appspot.com",
messagingSenderId: "103854538000",
appId: "1:103854538000:web:9c77e5a5f7de0c3cb7f995"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
export { auth, db };
so this is my previous way of doing it
You are mixing Firebase SDKs V8 and V9 syntax.
const authUser = await createUserWithEmailAndPassword(...) is V9 syntax
while
db.collection("users").add(...) is V8 syntax.
Adapting your code as follows should do the trick. I don't know how you defined the firebase Object you pass to the createUserWithEmailAndPassword() method, so I included all the imports and initialization code. It's up to you to adapt this part.
import { initializeApp } from "firebase/app";
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
import { getDatabase, collection, addDoc } from "firebase/firestore";
const app = initializeApp(firebaseConfig);
const onSignUp = async (email, password, username) => {
try {
const auth = getAuth(app);
const authUser = await createUserWithEmailAndPassword(
auth,
email,
password
);
const db = getDatabase(app);
await addDoc(collection(db, "users"), {
owner_uid: authUser.user.uid,
usernames: username,
email: authUser.user.email,
profile_pic: await randomProfiles()
});
this.props.phase(0);
} catch (error) {
console.log(error);
}
};
When I try to perform google authentication with firebase, neither the googleSignInWithPopup method works, nor with any other. I am following the instructions in the documentation and nothing appears
about this error.
It does not throw any error and all functions are called
this is the code I am implementing:
const firebaseConfig = {
apiKey: "AIzaSyBTtZRgAufHwkuth3Jo-pnTTKl1tBrK92o",
authDomain: "journal-react-redux.firebaseapp.com",
projectId: "journal-react-redux",
storageBucket: "journal-react-redux.appspot.com",
messagingSenderId: "189133948252",
appId: "1:189133948252:web:99aaaedf42fdb97243ed99"
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
export {
db,
googleAuthProvider,
firebase
}
export const startGoogleLogin = () => {
return (dispatch) => {
firebase.auth().signInWithRedirect(googleAuthProvider)
.then(({ user }) => {
dispatch(
login(user.uid, user.displayName)
)
});
}
}
export const login = (uid, displayName) => {
return {
type: types.login,
payload: {
uid,
displayName
}
}
}
const handleGoogleLogin = () =>{
dispatch(startGoogleLogin);
}
this is all the code where it is used and declared for use.
PS: This app is made in react 17 with redux.
Could you try this code snippet? Also, make sure that Google Authentication is enabled in Firebase Console
export const loginUserWithGoogle = () => {
const provider = new firebase.auth.GoogleAuthProvider();
return auth
.signInWithPopup(provider)
.then((result) => {
return result.user;
})
}
Then you can use this code in your actions
export const logInWithGoogle = () => {
return (dispatch) => {
loginUserWithGoogle()
.then((user) => {
// ... do something with user
})
.catch(error => {
console.log(error)
})
}
}
Try to update your function to
const handleGoogleLogin = () => {
return (dispatch) => {
dispatch(startGoogleLogin);
}
}
i have i problem with this file.js ; i try to start the application but the console give me the error on the title of this post (TypeError: _firebase.default.analytics is not a function. (In '_firebase.default.analytics()', '_firebase.default.analytics' is undefined)). I'm using firebase ase database and React Native to create this app based on a common chat where differents user can join and pass messages; This is the code:
import firebase from 'firebase';
import { useCallback } from 'react';
class Fire {
constructor() {
this.init()
this.checkAuth()
}
init = () => {
if(!firebase.apps.length){
var firebaseConfig = {
apiKey: "AIzaSyCSptHIogcurTROMvzp_QB7vQ8srIbnwBk",
authDomain: "login-with-firebase-23e8e.firebaseapp.com",
projectId: "login-with-firebase-23e8e",
storageBucket: "login-with-firebase-23e8e.appspot.com",
messagingSenderId: "1099034898191",
appId: "1:1099034898191:web:b8a3a66be2d5a49d83987a",
measurementId: "G-73M58E50QL"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
}
};
checkAuth = () =>{
firebase.auth().onAuthStateChanged(user => {
if(!user){
firebase.auth().signInAnonymously();
}
});
};
send = messages => {
messages.forEach(item => {
const message = {
text: item.text,
timestamp: firebase.database.ServerValue.TIMESTAMP,
user: item.user
}
this.db.push(message)
})
};
get db() {
return firebase.database().ref("messages");
};
parse = message => {
const {user, text, timestamp} = message.val()
const {key: _id} = message;
const createdAt = new Date(timestamp);
return {
_id,
createdAt,
text,
user
};
}
get = callback => {
this.db.on("child_added", snapshot => callback(this.parse(snapshot)));
};
get uid(){
return (firebase.auth().currentUser || {}).uid;
}
}
export default new Fire();
I guess that my store from vuejs is resetting my authorization. I also get the error message Cannot read property 'home' of undefined in the header component. I don't know why this is not working. I tried debugging.
This is what i have:
In my nuxt.config.js i set plugins to firebase:
plugins: [
'~/plugins/firebase.js'
],
Then here is my firebase.js file:
import firebase from 'firebase/app'
import 'firebase/auth'
var firebaseConfig = {
apiKey: "MYAPIKEY",
authDomain: "AUTHDOMAIN",
databaseURL: "DBURL",
projectId: "PROJECTID",
storageBucket: "STORAGEBUCKET",
messagingSenderId: "MESSAGINGSENDERID",
appId: "APPID",
measurementId: "MEASUREMENTID"
};
!firebase.apps.length ? firebase.initializeApp(firebaseConfig) : ''
export const auth = firebase.auth()
export default firebase
I don't know if it has anything to do with my error but for purpose i just put it in.
Then for my registration page i registrate users with their gmail account i have a function in methods like this:
async registersocial() {
try {
const provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then((result) => {
this.account.email = result.user.email
this.account.naam = result.additionalUserInfo.profile.given_name
this.account.achternaam = result.additionalUserInfo.profile.family_name
this.$store.dispatch('users/registersocial', this.account).catch(err => {
this.errmsg = err
})
});
} catch(err) {
this.errmsg = err
}
}
And this fires to the store to register a user set a cookie and set the user in the store i do it like so:
async registersocial({ commit }, account) {
const token = await auth.currentUser.getIdToken();
const { email, uid } = auth.currentUser;
Cookie.set('access_token', token);
commit('SET_USER', {
email,
uid
});
this.$router.push('profiel')
const users = firebase.database().ref('Gebruikers/')
users.once('value', function(snapshot){
const naam = account.naam
const achternaam = account.achternaam
const email = account.email
const google = "Google"
var sameemail = null
snapshot.forEach(function(childSnapshot) {
const data = childSnapshot.exportVal()
if(data.Email == email) {
sameemail = email
}
})
if(sameemail != email) {
users.push({
Voornaam: naam,
Achternaam: achternaam,
Email: email,
registerMethod: google
})
}
})
}
And then for the cookie i set i do this:
import JWTDecode from 'jwt-decode';
import cookieparser from 'cookieparser';
export const actions = {
nuxtServerInit({commit}, {req}) {
if(process.server && process.static) return;
if(!req.headers.cookie) return;
const parsed = cookieparser.parse(req.headers.cookie);
const accessTokenCookie = parsed.access_token;
if(!accessTokenCookie) return;
const decoded = JWTDecode(accessTokenCookie);
if(decoded) {
commit('users/SET_USER', {
uid: decoded.user_id,
email: decoded.email
})
}
}
}
Please let me know what i am doing wrong. If u need any more code please let me know.
I'm trying to do a query to the database, to get all documents of sub-collection "roles" to redirect to different routes.
let userRef1 = db.collection('users').doc(currentUser.uid).collection('roles')
let cont = 0
let rol = ''
let rolStatus = ''
userRef1.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
cont++
rol = doc.data().rol
rolStatus = doc.data().status
});
import { firestore } from "../../firebase";
export const loadCategories = () => {
return (dispatch, getState) => {
firestore
.collection("CATEGORIES")
.get()
.then((querySnapshot) => {
if (!querySnapshot.empty) {
querySnapshot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
});
}
})
.catch((error) => {
console.log(error);
});
};
};
I have a collection of users including uid just like yours. And for each user, it contains a sub-collection called friends.
Currently, I'm using the following code for my project without having any issues.
module.exports = ({ functions, firestore }) => {
return functions.firestore.document('/users/{uid}').onDelete((event) => {
const userFriendsRef = getFriendsRef(firestore, uid);
userFriendsRef.get().then(snapshot => {
if (snapshot.docs.length === 0) {
console.log(`User has no friend list.`);
return;
} else {
snapshot.forEach(doc => {
// call some func using doc.id
});
}
}
}
};
function getFriendsRef(firestore, uid) {
return firestore.doc(`users/${uid}`).collection('friends');
}
Give it a try to fix your code from
db.collection('users').doc(currentUser.uid).collection('roles')
to
db.doc(`users/${currentUser.uid}`).collection('roles')
It is not clear what you are doing with the rol and status variables. You have declared them as though you are storing a single value, yet you are returning an array of roles and iterating through them.
With regards to getting the results, if your browser supports ES6, then you could do the following:
let userRef1 = db.collection(`users/${currentUser.uid}/roles`)
let cont = 0
let rol;
let rolStatus;
return userRef1.get()
.then(querySnapshot => {
// Check if there is data
if(!querySnapshot.empty) {
// Create an array containing only the document data
querySnapshot = querySnapshot.map(documentSnapshot => documentSnapshot.data());
querySnapshot.forEach(doc => {
let {rol, status} = doc;
console.log(`rol: ${rol} - status: ${status}`);
});
} else {
console.log('No data to show');
}
})
.catch(err => {
console.error(err);
});
Please note: I've only tested this with the Node SDK
// Firebase App (the core Firebase SDK) is always required and must be listed first
import * as firebase from "firebase/app";
// Add the Firebase products that you want to use
import "firebase/auth";
import "firebase/firestore";
const firebaseConfig = {
apiKey: "AIzaSyDNdWutrJ3Axpm-8ngNhzkzcw1g3QvkeFM",
authDomain: "books-7bd8b.firebaseapp.com",
databaseURL: "https://books-7bd8b.firebaseio.com",
projectId: "books-7bd8b",
storageBucket: "books-7bd8b.appspot.com",
messagingSenderId: "385706228283",
appId: "1:385706228283:web:a3c2c9585dd74d54693a1e",
};
firebase.initializeApp(firebaseConfig);
export const firebaseAuth = firebase.auth();
export const firestore = firebase.firestore();
export default firebase;
You should check if it always exists before doing your logic:
userRef1.get().then(function(querySnapshot) {
if(querySnapshot)
{
querySnapshot.forEach(function(doc) {
...you thing
}
})