reactjs and firebase function db (database) not working on running - javascript

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);
}
};

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.

Node Modules / Working with Firebase in Node Js - how to retrieve images in node js

I have an html page that can view images from my firebase app. However, this also exposes my firebase credentials as its client side.
What I'd like to do is accomplish the same in node js. but have issues/lack of understanding of node modules.
here is my redacted HTML/javascript
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.12.1/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.12.1/firebase-analytics.js";
import { getAuth } from 'https://www.gstatic.com/firebasejs/9.12.1/firebase-auth.js'
import { getFirestore, collection, addDoc,getDocs, doc, updateDoc, deleteDoc } from 'https://www.gstatic.com/firebasejs/9.12.1/firebase-firestore.js'
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from 'https://www.gstatic.com/firebasejs/9.12.1/firebase-storage.js'
const param = {
apiKey:"mykey",
authDomain: "xxxm",projectId: "mobxxxes",storageBucket: "mobxxxxxt.com",messagingSenderId: "83xxxx7",
appId: "1:xxx2047:web:79xxx7a",measurementId: "G-ZxxxxxxxxH"
};
const app = initializeApp(param);
const analytics = getAnalytics(app);
const db = getFirestore(app);
const storage = getStorage(app);
async function loadImages(){
let querySnapshot = await getAllData();
let divPag = $("#uploaded_images");
setTimeout(()=>{
querySnapshot.forEach((doc) => {
myImageSrc.push(imageSrc(doc.data(),doc.id));
myImageDes.push(imageDescription(doc.data(),doc.id));
});
},1000)
}
function imageSrc(image,i){
let data =`${image["src"]}`
return data;
}
function imageDescription(image,i){
let data =`${image["description"]}`
return data;
}
loadImages();
})
Tried to accomplish in node but errors regarding modules/importing
in package.json add
"type":"module",
as for the rest of the node console app use the following and change credentials
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
// Follow this pattern to import other Firebase services
// import { } from 'firebase/<service>';
let myArr = [];
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
//my creds here
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// Get a list of cities from your database
async function getCities() {
const citiesCol = collection(db, "uploadedimages");
const citySnapshot = await getDocs(citiesCol);
const cityList = citySnapshot.docs.map(doc => doc.data());
myArr.push(cityList);
console.log(myArr[0][0].src)
//return cityList;
}
getCities();

React Native Expo Firebase Auth not working on Version 9

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

How do you create a subcollection in Firebase Firestore?

I'm having troulbe figuring out how to add a subcollection to a document in my React App. I'm also getting the error that db.collection() is not a function. I'm trying to add the subcollection in the registerWithEmailAndPassword function. The Firebase Firestore documentation does not specify how to create a subcollection. Any help would be greatly appreciated thank you. Firebase config has been ommited to protect my API key.
import { initializeApp } from "firebase/app";
import {
GoogleAuthProvider,
getAuth,
signInWithPopup,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
sendPasswordResetEmail,
signOut,
} from "firebase/auth";
import {
getFirestore,
query,
getDocs,
collection,
where,
addDoc,
Firestore,
doc,
DocumentReference,
setDoc
} 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
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const googleProvider = new GoogleAuthProvider();
const signInWithGoogle = async () => {
try {
const res = await signInWithPopup(auth, googleProvider);
const user = res.user;
const q = query(collection(db, "users"), where("uid", "==", user.uid));
const docs = await getDocs(q);
if (docs.docs.length === 0) {
await addDoc(collection(db, "users"), {
uid: user.uid,
name: user.displayName,
authProvider: "google",
email: user.email,
});
}
} catch (err) {
console.error(err);
alert(err.message);
}
};
const logInWithEmailAndPassword = async (email, password) => {
try {
await signInWithEmailAndPassword(auth, email, password);
} catch (err) {
console.error(err);
alert(err.message);
}
};
const registerWithEmailAndPassword = async (name, email, password) => {
try {
const res = await createUserWithEmailAndPassword(auth, email, password);
const user = res.user;
const userDoc = await addDoc(collection(db, "users"), {
uid: user.uid,
name,
authProvider: "local",
email,
});
db.collection("users").doc(userDoc.id).collection("test");
} catch (err) {
console.error(err);
alert(err.message);
}
};
const sendPasswordReset = async (email) => {
try {
await sendPasswordResetEmail(auth, email);
alert("Password reset link sent!");
} catch (err) {
console.error(err);
alert(err.message);
}
};
const logout = () => {
signOut(auth);
};
export {
auth,
db,
signInWithGoogle,
logInWithEmailAndPassword,
registerWithEmailAndPassword,
sendPasswordReset,
logout,
};
This code uses the classic, namespaced syntax of Firebase SDK version 8 and before:
db.collection("users").doc(userDoc.id).collection("test");
But the rest of your code uses the new modular syntax of Firebase SDK versions 9 and later. The equivalent there would be:
collection(doc(collection(db, "users"), userDoc.id), "test")
Or more concisely:
collection(db, "users", userDoc.id, "test")
The above creates a reference to the subcollection, but doesn't create the collection in the database yet. A collection is created once a document is written to it, and removed automatically once the last document is removed from it.
So you can create a document in test (and thus create test) with:
const testCollection = collection(db, "users", userDoc.id, "test");
addDoc(testCollection, { title: "hello world })

How to update data in Firebase realtime database using Firebase 9 (modular sdk)

How do we do this now:
import "firebase/database"
await firebase
.database()
.ref('users/' + auth.currentUser.uid)
.update({
displayName: displayName
});
That should do:
import firebase from "firebase/compat/app";
import {update, ref, getDatabase} from "firebase/database"
const app = firebase.initializeApp(firebaseConfig);
const db = getDatabase(app)
const dbRef = ref(db, `users/{userUid}`)
update(dbRef, {displayName: "Firebase9_IsCool"}).then(() => {
console.log("Data updated");
}).catch((e) => {
console.log(e);
})

Categories