Firebase db with vuejs : default.collection is not a function - javascript

I'm starting a small project with Vuejs and Firebase. I am trying to upload Name and Price to Firestore. I checked their documentation and few tutorials, but I am stuck with this error.
<div class="form-group">
<v-btn v-on:click="saveData" class="btn btn-primary">Save data</v-btn>
</div>
import db from "../firebase";
export default {
name: "products",
props: {
msg: String,
},
data() {
return {
aon: {
Name: null,
Price: null,
},
};
},
methods: {
saveData() {
db.collection("Products")
.add(this.Product)
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
},
},
};
Here is my firebase.js
import firebase from '#firebase/app';
import '#firebase/auth';
import '#firebase/firestore';
const fb = firebase.initializeApp({
apiKey: "!!!!!!!!!!!",
authDomain: "!!!!!!!!",
databaseURL: "!!!!!!!",
projectId: "!!!!!!",
storageBucket: "!!!!!!!",
messagingSenderId: "!!!!!!!",
appId: "!!!!!!!!!",
measurementId: "!!!!!!!!!!!!"
});
const db = firebase.firestore();
export default firebase;
export {db,fb} ;

First you didn't initialized your firebase app. To do so :
//firebase.js
const db = firebase.initializeApp(fb)
export {db.firestore(),fb}
Then on your products page or component you wrote :
//products.vue
db.collection("Products").add(this.Product)...
this.Product object doesn't exist so it should be this.aon
//products.vue
db.collection("Products").add(this.aon)...
For more info : https://firebase.google.com/docs/firestore/quickstart

As per the documentation here and here you need to use the .set(), .add(), .update() and .doc() methods like this.
When you use set() to create a document, you must specify an ID for the document to create. For example:
await db.collection('cities').doc('new-city-id').set(data);
to let Cloud Firestore auto-generate an ID for you. You can do this by calling add()
// Add a new document with a generated id.
const res = await db.collection('cities').add({
name: 'Tokyo',
country: 'Japan'
});
console.log('Added document with ID: ', res.id);
In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc()
const newCityRef = db.collection('cities').doc();
// Later...
const res = await newCityRef.set({
// ...
});
To update some fields of a document without overwriting the entire document, use the update() method:
const cityRef = db.collection('cities').doc('DC');
// Set the 'capital' field of the city
const res = await cityRef.update({capital: true});

Related

Firebase auth google provider popup (and redirect) gives blank page

I have been trying to set up firebase auth for my next js project, and while it works to sign in and login with email og password, google sign in does not, it opens popup (or redirects if use signInWithRedirect()) but the popup is empty. Does not show my google accounts. Just loads an empty screen from 'https://project.firebaseapp.com/__/auth/handler?apiKey=blablabla&appName=%5BDEFAULT%5D&authType=signInViaPopup&redirectUrl=http%3A%2F%2Flocalhost%3A3000%2Flogin&v=9.16.0&providerId=google.com&scopes=profile'
A weird part is that it worked for a short while earlier, but then at some point it stopped, and I don't now what I changed, if I changed anything at all. Tried resetting back to old code, and also setting up new firebase project, but does not work anymore.
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
export const firebaseConfig = {
apiKey: "blabla",
authDomain: "project.firebaseapp.com",
projectId: "project",
storageBucket: "project.appspot.com",
messagingSenderId: "blabla",
appId: "blabla",
measurementId: "blabla"
}
// Use this to initialize the firebase App
export const firebaseClient = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
// Use these for db & auth
export const db = firebaseClient.firestore()
export const auth = firebaseClient.auth()
export const googleProvider = new firebase.auth.GoogleAuthProvider()
export default firebaseClient
this is signin functions (with mail & password works):
function signIn(e: React.MouseEvent<HTMLElement>) {
e.preventDefault()
if (emailRef.current && passwordRef.current) {
auth.signInWithEmailAndPassword(
emailRef.current.value,
passwordRef.current.value
).then((authUser) => {
console.log(authUser)
router.push('/dashboard/profile')
})
.catch((error) => {
alert(error.message)
})
console.log("signin", emailRef.current.value, passwordRef.current.value)
}
}
function signInGoogle(e: React.MouseEvent<HTMLElement>) {
e.preventDefault()
auth.signInWithRedirect(googleProvider)
.then((authUser) => {
console.log(authUser)
router.push('/dashboard')
})
.catch((error) => {
alert(error.message)
})
}
EDIT:
Here is some more info:
The only errors I get are these cookie issues:
I also however get another error when connecting to my firestore, which maybe is correlated??
this is the code for that (which logs no products...):
useEffect(()=>{
db.collection('products').where('active','==', true).get()
.then((querySnapshot) => {
querySnapshot.forEach(async (product) => {
console.log(product.data);
})
})
.catch((error) => {
alert(error.message)
})
}, [])

Why is the data stored in firestore not being fetched in react?

I am trying to get data from firestore in react but I get the following in console(no data):
t {vf: e, m_: t, xf: null, $f: false, kf: false, …}
$f: false
T_: null
kf: false
m_: t {path: n}
vf: e {uf: n, hf: e, lf: FirebaseAppImpl, _f: e, INTERNAL: {…}, …}
xf: null
exists: (...)
id: (...)
metadata: (...)
ref: (...)
proto: Object
My firebase Setup
import firebase from "firebase";
const firebaseConfig = firebase.initializeApp({
apiKey: "AIzaSyDTpOEQVLZFezpUNDMPmh0FckcQmDQp_rQ",
authDomain: "ecommerce-app-f6a42.firebaseapp.com",
databaseURL: "https://ecommerce-app-f6a42.firebaseio.com",
projectId: "ecommerce-app-f6a42",
storageBucket: "ecommerce-app-f6a42.appspot.com",
messagingSenderId: "455019623318",
appId: "1:455019623318:web:2d90e3539b53ed939663b7",
measurementId: "G-BJGR6HPE48",
});
const db = firebaseConfig.firestore();
export default db;
Using db to get the data from firestore and consoled it:
import db from './firebase';
componentDidMount() {
db.collection("Products").onSnapshot((snap) => console.log(snap));
}
Data is being fetched just fine. You're logging an object whose contents are obfuscated.
snap is a QuerySnapshot type object. You should work with it as you see in the linked API documentation. I also suggest reading the primary product documentation for examples on how to process query results. Minimally, you should iterate the DocumentSnapshot objects contained in that QuerySnapshot, and consider logging the document data within each one.
Here is an example from the documentation:
db.collection("cities").where("state", "==", "CA")
.onSnapshot(function(querySnapshot) {
var cities = [];
querySnapshot.forEach(function(doc) {
cities.push(doc.data().name);
});
console.log("Current cities in CA: ", cities.join(", "));
});
Here is another one using a simpler get() operation rather than a realtime listener:
db.collection("cities").where("capital", "==", true)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});

React Native - Firestore: Possible Unhandled Promise Rejection Can't find variable atob

I'm working on a mobile app with react native and firebase, and I'm trying to store some information into firestore. but the function add() doesn't acctually add to the firestore, and I only get a worning when I click the buttton without any further reaction. The idea of my code is to take information from the user about an event then store it in firebase.
Here's the function I'm using to send information of the event and call [addEvent] function from the firebase API:
handleForm = () => {
var formData = {
name: this.state.eventName,
event_type: this.state.eventType,
age_group: this.state.ageGroup,
city: this.state.city,
date: this.state.date,
free: this.state.free,
adult_price: this.state.adultTicket,
kid_price: this.state.kidTicket,
location: this.state.eventLocation,
organizer: this.state.eventOrganizer,
description: this.state.eventDescription,
}
addEvent(formData);
}
which I'm calling it from a button
<Button onPress={() => this.handleForm()}>
and here is the firebase API code:
import * as fb from 'firebase';
import 'firebase/firestore';
import 'firebase/storage';
const config = {
apiKey: '**************************************',
authDomain: '**************************************',
databaseURL: '**************************************',
projectId: '**************************************',
storageBucket: '**************************************',
messagingSenderId: '**************************************',
appId: '**************************************',
measurementId: '**************************************',
};
const firebase = fb.initializeApp(config);
const db = firebase.firestore();
export function addEvent(event) {
db.collection('events')
.add(event)
.then((data) => {
console.log('Your Event successfully added!');
}).catch((error) => console.log('Error!'));
}
so I'm getting this warning, and nothing was printed in the console also the data was not added to the firestore
Warning: Possible Unhandled Promise Rejection (id: 0):
ReferenceError: Can't find variable: atob
I'm using:
React Native: version 0.61.5
Firebase: version 7.11.0
in your app.js file,import 'base-64' globally:
import {decode, encode} from 'base-64';
if (!global.btoa) { global.btoa = encode }
if (!global.atob) { global.atob = decode }

Cannot query from Firebase for my React Native app?

It seems I can retrieve all my data from my Firebase Realtime Database with the following:
let itemsRef = firebaseApp.database().ref('/');
itemsRef.on('value', (snapshot) => {
let data = snapshot.val();
let item = Object.values(data);
this.setState({item});
});
But when I try to query with specific parameters instead of just retrieving all the information, I always end up with this error:
#firebase/database: FIREBASE WARNING: Exception was thrown by user callback.
TypeError: Cannot convert undefined or null to object
This is how I'm trying to query information... literally following the documentation, and somehow my code works when I retrieve all information but not when the only change I make is adding a query?
let itemsRef = firebaseApp.database().ref('/');
itemsRef.orderByChild('roundedBPM').equalTo('100').on('value', (snapshot) => {
let data = snapshot.val();
let item = Object.values(data);
this.setState({item});
});
Is anyone else having problems querying from Firebase or am I doing something wrong?
This is how my data is structured on Firebase:
I would try initializing firebase in dbConfig.js for instance like so:
import * as firebase from 'firebase';
let config = {
apiKey: "XXXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXX"
};
firebase.initializeApp(config);
export default firebase;
I would import firebase where it's:
import firebase from './dbConfig.js'
let itemsRef = firebase.database().ref('/');
itemsRef.orderByChild('roundedBPM').equalTo('100').on('value', (snapshot) => {
let data = snapshot.val();
let item = Object.values(data);
this.setState({item});
});
Note: OrderByChild the element roundedBPM needs to be a direct child to the root path '/' if it's a nested child you could do something like this:
let itemsRef = firebase.database().ref('/users');
itemsRef.orderByChild('roundedBPM').equalTo('100').on('value', (snapshot) => {
...
});
Note: if you are setting equalTo() roundedBPM when it's a number and not a string you wouldn't get back any data. Make sure you use the correct type of data.
I hope this will help!

Is it possible to define a variable on the firebase database references path?

I am trying to redefine all my apps database references so that I can write a specific set of of firebase rules (I need to add buildings and depts nodes inside the user node – read why: What is the best practice to write the rules of Firebase in a situation like this? ).
I am using a firebase-config.js and exporting all my app's database references to the app's components so hopefully if I change this path I don't have to refactor the code on all the app's components.
I am trying to do it with a function (on my firebase-config.js file):
import * as firebase from "firebase";
import { mapState } from 'vuex';
import { store } from './store/store';
var config = {
apiKey: "XXXXXXXX",
authDomain: "XXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXX.firebaseio.com",
projectId: "XXXXXXXX",
storageBucket: "XXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXX"
};
firebase.initializeApp(config)
export default !firebase.apps.length ? firebase.initializeApp(config) : firebase;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
let userRef = firebase.database().ref('users').child(user.uid);
let buildingsRef = userRef.child('buildings');
}
})();
export const db = firebase.database();
export const usersRef = db.ref('users');
_// BUT THIS: "buildingsRef" is returning undefined!!! :(
export const buildingsRef = db.ref('users'+ "/" + buildingsRef) //buildingsRef is a variable
export const deptsRef = db.ref('depts');
The buldingsRef variable is returning undefined and it's writing the buildings to an undefined node.
{
"users" : {
"6hwNde08Wuaa9bfReR28niSbOsF3" : {
"name" : "João Alves Marrucho",
"userEmail" : "joaoalvesmarrucho#hotmail.com"
},
"undefined" : {
"-L9M4lM7oZFfmJKorxjC" : {
"address" : "",
"name" : "b1",
"ownerID" : "6hwNde08Wuaa9bfReR28niSbOsF3"
}
}
}
}
I writing to the node with the following method (vue.js):
addBuilding: function () {
let userId = firebase.auth().currentUser.uid;
let buildingKey = buildingsRef.push().key
this.newBuilding.ownerID = userId;
buildingsRef.child(buildingKey).set(this.newBuilding);
}
Any thoughts on why the variable buildingsRef is returning undefined?
Here is my full firebase-config.js file: http://jsfiddle.net/UnXrw/85/
If I understand your question, I think you want something like this:
firebase.auth().onAuthStateChanged(user => {
if (user) {
let userRef = firebase.database().ref('users').child(user.uid);
let buildingsRef = userRef.child('buildings');
// now do whatever you want with those refs
}
});

Categories