uid not getting saved in firebase database - javascript

import React from 'react'
import firebase from 'firebase';
const config = {
apiKey: "***",
authDomain: "***",
databaseURL: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
const fire = firebase.initializeApp(config);
export default class SignUp extends React.Component {
state = { email: '', password: '', userName: '', errorMessage: null };
constructor(props) {
super(props);
}
handleSignUp = () => {
const { userName, email, password } = this.state;
firebase.
auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(authUser => {
this.props.fire.database().ref('/users/')
.child(authUser.user.uid)
.set({
userName,
email,
});
})
.then(() => this.props.navigation.navigate('message'))
.catch(error => this.setState({ errorMessage: error.message }))
}
}
my db is not getting updated with username and email.
1.New with database handling and react so mostly
must be using database functions incorrectly
2.Please check handlesignup function
3.Data of firebase authentication is getting update properly
uid and user mail are displayed properly
4.part where uid is saved which is not working
.then(authUser => {
this.props.fire.database().ref('/users/')
.child(authUser.user.uid)
.set({
userName,
email,
});
})

If you do
firebase.auth()
you should similarly do
firebase.database().ref('/users/')
.child(authUser.user.uid)
.set({...})
since firebase is "a global namespace from which all Firebase services are accessed", see https://firebase.google.com/docs/reference/js/firebase

Related

Uncaught FirebaseError: Invalid document reference. Document references must have an even number of segments, but todos has 1

I'm getting the error:
Uncaught FirebaseError: Invalid document reference. Document references must have an even number of segments, but todos has 1.
I wrote code because I want to inquire the data in the DB.
No matter how much I searched, I couldn't find the answer. which part is wrong
this is my firebaseConfig code:
import firebase from "firebase/compat/app";
import "firebase/compat/firestore";
import "firebase/compat/auth";
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***",
};
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
export { firestore };
export const auth = firebase.auth();
export const apiKey = firebaseConfig.apiKey;
this is code of firebaseController.tsx:
export const todos = firestore.collection('todos');
and this is code of view component:
useEffect(() => {
onSnapshot(todos, (snapshot: QuerySnapshot<DocumentData>) => {
setTodoItems(
snapshot.docs &&
snapshot.docs.map((doc) => {
return {
id: doc.id,
...doc.data(),
};
})
);
});
}, []);
my database:
DB
The onSnapshot method works on Firebase Documents, not on Firebase Collections. The first argument to onSnapshot you give i.e. "todos" is a collection reference but in reality, it expects a document reference, which you obtain by using the method
const docRef = doc(db, "path/to/document/inside/todos/collection")
onSnapshot(docRef, ......)
Hope this helps!

Cannot register user info to firebase database when creating a new user

I am working on a signup form and I can create a new user using firebase auth, but the part where I register informations like the name, email... in a database is not working.
On the firebase side, I created a firestore database and a realtime database, and I don't see anything on them.
I tried to use the firebase documentation but it's still not working so I am probably missing something.
Thanks for your help!
PS: I hidded my firebase config here but it's filled on my code
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js'
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js'
import { getFirestore, doc, getDoc, getDocs, collection } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const app = initializeApp(firebaseConfig);
//const db = getFirestore();
const auth = getAuth();
const db = getDatabase();
submitData.addEventListener('click', (e) => {
e.preventDefault()
var name = document.getElementById('full_name').value
var email = document.getElementById('email').value;
var password = document.getElementById('psw').value;
// do verification
// Move on with Auth
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user
alert("user created")
//add to firebase database
function writeUserData( name, email) {
set(ref(db, 'users/' + userId), {
username: name,
email: email,
});
}
})

Why am I unable to sign in anonymously as an authenticated user in firebase?

I am trying to login as an authenticated user anonymously. Here is my code:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getAuth, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-auth.js";
const firebaseConfig = {
apiKey: "key_here",
authDomain: "project.firebaseapp.com",
projectId: "project",
storageBucket: "project.appspot.com",
messagingSenderId: "id_here",
databaseURL: "https://project-default-rtdb.firebaseio.com",
appId: "app_id_here"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
document.getElementById("login").addEventListener("click",function(event){
event.preventDefault();
onAuthStateChanged(auth, (user) => {
if(user){
//user can successfully login
}
else{
console.log("Something went wrong");
}
}, (error) => console.error(error)) //Nothing prints here
}
I was able to successfully log in 'til yesterday. But since this morning I keep getting the error Something went wrong in my console.
I didn't change anything in the code, nor in my firebase credentials. Where am I going wrong?
It was so silly of me to not read the documentation page carefully, I had forgotten to execute the signInAnonymously() method before checking for the user's data, the complete code is as follows:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getAuth, onAuthStateChanged, signInAnonymously } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-auth.js";
const firebaseConfig = {
apiKey: "key_here",
authDomain: "project.firebaseapp.com",
projectId: "project",
storageBucket: "project.appspot.com",
messagingSenderId: "id_here",
databaseURL: "https://project-default-rtdb.firebaseio.com",
appId: "app_id_here"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
document.getElementById("login").addEventListener("click",function(event){
event.preventDefault();
signInAnonymously(auth)
.then(() => {
onAuthStateChanged(auth, (user) => {
if(user){
//user can successfully login
}
else{
console.log("Something went wrong");
}
});
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorCode+": "+errorMessage);
});
});

Firebase firestore not working react native

I have a react native project configured with firebase and the firestore db is not working. It doesnt show any errors either.
Here is my firebase config file:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth'
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
databaseURL: "",
};
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig);
app.firestore().settings({ experimentalForceLongPolling: true });
} else {
app = firebase.app();
app.firestore().settings({ experimentalForceLongPolling: true });
}
const db = app.firestore();
const auth = app.auth();
export {db, auth }
Here is my code that i use to authenticate user than save it to firestore:
const signup = dispatch => async (email, password) => {
try {
await auth.createUserWithEmailAndPassword(email, password).then(async resp => {
});
await db.collection('users').add({
email: 'asdas',
uid: 'asdsda',
coins: 0,
}).catch(error => {
console.log(error);
});
} catch (error) {
console.log(error);
alert(error.message);
}
};
Firestore rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read,write: if
request.time < timestamp.date(2022, 9, 21);
}
}
}
The authentication part works perfectly but the firestore code doesnt execute. Any idea why this is happening?

TypeError: _app.default.auth is not a function - React Native Web - Firebase

I am currently developing a project on React Native Web and this is my login call in a component. (The call is in the components useEffect, as soon as the component opens, it should log in anonymously)
import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
const firebaseConfig = {
apiKey: "****",
authDomain: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
};
firebase.initializeApp(firebaseConfig)
const login = async () => {
firebase.auth().signInAnonymously()
.then((userCredential) => {
// Signed in
// ...
})
.catch((error) => {
console.log("LOG: "+error)
});
}
But everytime I get the error: Uncaught (in promise) TypeError: _app.default.auth is not a function
I tried several different imports, but none of them seemed to work.
I see the error when I open the Console on Firefox. How can I fix this issue?
Thanks
Try this approach by checking if firebase is initialized and the user is not logged in:
const [loggedIn, setLoggedIn] = React.useState(false)
React.useEffect(() => {
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: "****",
authDomain: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
});
}
}, [])
React.useEffect(() => {
if (firebase.apps.length && !loggedIn) {
setLoggedIn(true)
login()
}
}, [firebase])
const login = async () => {
firebase.auth().signInAnonymously()
.then((userCredential) => {
// Signed in
// ...
})
.catch((error) => {
console.log("LOG: " + error)
});
}

Categories

Resources