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
}
})
Related
I'm a junior dev, so please be easy with me.
My goal is to auth an user anonymously when he open the homepage, then if all went ok, he fetch the data from the real time database, but only if the uid match is ok!
He there are my rules:
{
"rules": {
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "false",
}
}
}
My database is structured like this https://ibb.co/jkRBCsF
The anonymous sign in is on the context
export const AuthContextProvider = ({ children }: Props) => {
React.useEffect(() => {
signInAnonymously(auth)
.then(() => {
// Signed in..
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ...
});
}, []);
const values = {};
return <AuthContext.Provider value={values}>{children}</AuthContext.Provider>;
};
Then when I open a page for example '/crew' getStaticProps launches fetchPlanetInfo
export const getStaticProps: GetStaticProps = async () => {
const planetInfo = await fetchPlanetsInfo("destinations");
return {
props: {
data: planetInfo,
},
};
};
export function fetchPlanetsInfo(query: string) {
let dataArr: any = [];
try {
onAuthStateChanged(auth, (user) => {
if (user) {
const uid = user.uid;
const databaseCall = ref(db, uid + "/" + query);
onValue(databaseCall, (snapshot) => {
const data = snapshot.val();
dataArr.push(data);
});
} else {
console.log("user is signout");
// User is signed out
// ...
}
});
} catch (error) {
console.log(error);
}
return dataArr.flat();
}
I tried to figure out where is the error but I didn't find out the solution
My problem is that the data is not get from the database. fetchPlanetsInfo return null. I think my rules is written wrong.
I am to make a blog website that can save and publish written articles within the website. I am using firebase firestore to save my data there but only problem is that when i run it, it say db is not defined at HTMLButtonElement
HTML
<script
type="module"
src="https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js"
></script>
<script
type="module"
src="https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js"
></script>
<script type="module" src="js/editor.js">
firebase.initializeApp({
apiKey: "AIzaSyBbHBS9rdHrbP6g7BG4_kPP9XV1vCiVewU",
authDomain: "blog-web-49668.firebaseapp.com",
projectId: "blog-web-49668",
storageBucket: "blog-web-49668.appspot.com",
messagingSenderId: "561111016179",
appId: "1:561111016179:web:eef336738659e3fbfb0d86",
});
var db = firebase.firestore();
db.settings({ timestampsInSnapshots: true });
</script>
Javascprit
publishBtn.addEventListener('click', () => {
if (articleField.value.length && blogTitleField.value.length) {
// generating id
let letters = 'abcdefghijklmnopqrstuvwxyz';
let blogTitle = blogTitleField.value.split("-").join("-");
let id = '';
for (let i = 0; i < 4; i++) {
id += letters[Math.floor(Math.random() * letters.length)];
}
// setting up docName
let docName = `${blogTitle}-${id}`;
let date = new Date(); // for published at info
//access firestore with db variable;
db.collection("blogs").doc(docName).set({
title: blogTitleField.value,
article: articleField.value,
bannerImage: bannerPath,
publishedAt: `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
})
.then(() => {
console.log('date entered');
})
.catch((err) => {
console.error(err);
});
}
})
You need to remove src="js/editor.js" from the script tag:
<script type="module" src="js/editor.js">
firebase.initializeApp({...
// ...
</script>
should be
<script type="module">
firebase.initializeApp({...
// ...
</script>
i have the same problem, i solve in this way
Hello, try to put this code in the "firebase.js":
let firebaseConfig = {
//your information
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export async function insert(item) {
try {
const response = await db.collection("blogs").add(item);
return response;
} catch (error) {
throw new Error(error);
}
}
export async function getItems(uid) {
try {
let items = [];
const response = await db
.collection("blogs")
.where("userid", "==", uid)
.get();
response.forEach(function (item) {
items.push(item.data());
});
return items;
} catch (error) {
throw new Error(error);
}
}
export async function update(id, completed) {
try {
let docId;
const doc = await db.collection("blogs").where("id", "==", id).get();
doc.forEach((i) => {
docId = i.id;
});
await db.collection("blogs").doc(docId).update({ completed: completed
});
} catch (error) {
throw new Error(error);
}
}
export { db };
and in the js files import:
import { insert, getItems, update, db } from "./firebase.js";
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.