Cannot read property forEach of null in reactNative and firebase - react-native-firebase

I am not getting error 'cannot read property 'forEach' null.
querySnapshot.forEach((doc) => {
const { title } = doc.data();
users.push({
title
});
});
setUsers(users);
setLoading(false);
});

Related

Error : firebase cloud funtion, firebase database

when i run this code in firebase cloud function, it got error "Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array." i know that the problems happen because the function return before the tokens haven been loaded then i use promises but didn't work.
.ref('/alertToUser/{userId}/{timestamp}')
.onCreate((snapshot, context) =>
{
const userId=context.params.userId
const userName=snapshot.val().userName
const timestamp=context.params.timestamp
const message=snapshot.val().message;
let promises = [];
var DeviceToken = [];
const payload = {
"data":{
"topic":"alertToUser",
"message" : message,
"timestamp" : `${timestamp}`,
"userName" : userName
}
};
const options = {
"priority":"high"
};
let promise=admin.database().ref(`alertToUser/${userId}/${timestamp}/recieverID`).once("value",(snapshot) => {
snapshot.forEach((userSnap) => {
var recieverID=userSnap.val();
admin.database().ref(`/User/${recieverID}/token`).once("value",(snapshot)=>{
var token= snapshot.val();
DeviceToken.push(token);
console.log(`token: ${DeviceToken}`);
})
});
return true;
}
)
promises.push(promise);
return Promise.all(promises).then(() => {return admin.messaging().sendToDevice(DeviceToken, payload,options);});
});

Updating displayed results after modifying Firestore doc React Native

I have a list of games that I'm able to add to without issue using UseEffect and onSnapshot. I can modify an item in the list without issue, and return one set of results (with the updated data properly displaying). When I try to modify another item (or the item same again), I get this error:
Could not update game: TypeError: undefined is not an object (evaluating '_doc.data().numPlayers') because the results/list of games are null. I'm sure I have something wrong with my code, but I can't figure it out.
Thanks in advance!
Here is my code:
useEffect(() => {
setIsLoading(true)
let results = [];
const unsubscribe = db
.collection('games')
.onSnapshot(
(querySnapshot) => {
querySnapshot.docChanges().forEach(change => {
const id = change.doc.id;
if (change.type === 'added') {
const gameData = change.doc.data();
gameData.id = id;
results.push(gameData);
}
if (change.type === 'modified') {
console.log('Modified game: ', id);
results = results.map(game => {
if (game.id === id) {
return change.doc.data()
}
return game
})
console.log(results)
}
if (change.type === 'removed') {
console.log('Removed game: ', id);
}
});
setIsLoading(false);
setGame(results);
return () => unsubscribe
},
(err) => {
setIsLoading(false);
console.log("Data could not be fetched", err);
}
);
}, []);
I forgot to add the doc ID to the gameData before adding it to the results. I did that in the "added" section, but not in the "modified" section (thinking that it was already included), forgetting that I hadn't added it as an actual field in the database (it just exists as the doc id).

null is not an object (evaluating 'snapshot.forEach')

I'm trying to subscribe to a query on firestore but I'm getting an error when I add a filter.
this works just fine
useEffect(() => {
if (dbChats && currentUser?.uid) {
const unsubscribe = dbChats
.orderBy('createdAt')
.limit(100)
.onSnapshot((querySnapshot) => {
const chats = firebaseLooper(querySnapshot);
setChats(chats);
});
return unsubscribe;
}
}, [dbChats]);
but this doesn't
useEffect(() => {
if (dbChats && currentUser?.uid) {
const unsubscribe = dbChats
.where('participants', 'array-contains', currentUser.uid)
.orderBy('createdAt')
.limit(100)
.onSnapshot((querySnapshot) => {
const chats = firebaseLooper(querySnapshot);
setChats(chats);
});
return unsubscribe;
}
}, [dbChats]);
whenever I add
where('participants', 'array-contains', currentUser.uid)
It throws the error
null is not an object (evaluating 'snapshot.forEach')
Note that this also works
dbChats.where('participants', 'array-contains', currentUser.uid).get()
The snapshot is null because you haven't supplied any error handling and the query is throwing an error. Simply supply an error handler as a second param to onSnapshot.
windowsill is correct. Once I properly supplied error handling I received the error from firebase [Error: [firestore/failed-precondition] The query requires an index. You can create it here: https://console.firebase.google.com/...
In my case I needed to add an index.
Change this:
firestore().collection("cities").where("state", "==", "CA")
.onSnapshot((querySnapshot) => {
var cities = [];
querySnapshot.forEach((doc) => {
cities.push(doc.data().name);
});
console.log("Current cities in CA: ", cities.join(", "));
});
To something like this:
firestore().collection('cities').where('state', '==', 'CA')
.onSnapshot({
error: (e) => console.error(e),
next: (querySnapshot) => {
var cities = [];
querySnapshot.forEach((doc) => {
cities.push(doc.data().name);
});
console.log('Current cities in CA: ', cities.join(', '));
}
});

Why is there a ReferenceError? Vue Firestore

Here is my code trying to fetch the user's information from the users collection in Firestore.
import db from "./firebaseInit";
import firebase from "firebase";
export default {
data() {
return {
uid: null,
user: null
};
},
created() {
if (firebase.auth().currentUser) {
// We're logged in
this.uid = firebase.auth().currentUser.uid;
console.log("The uid is: ", this.uid);
}
var docRef = db.collection("users").doc(this.uid);
docRef
.get()
.then(doc => {
if (doc.exists) {
this.user = doc.data(); // This is the line with the ReferenceError
console.log("This user is: ", user);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
})
.catch(function(error) {
console.log("Error getting document:", error);
});
},
methods: {
updateProfile() {
var docRef = db
.collection("users")
.doc(this.uid)
.update(this.user);
}
}
};
I am getting the following error in the catch block, although I have verified that the doc exists and is getting fetched. However, I seem not to be able to access my user variable defined in the data. This is the error:
Error getting document:
ReferenceError: user is not defined
Please let me know if you have any idea what might be happening.

Can't access to a collection from a looped collection

I want to access to a collection inside another collection in a for loop.
Is it possible? I'm getting an error at the 4th line Error getting documents TypeError: cookUser is not a function
var mealsOnline = [];
return db.collection('users').get().then(function (snapshot) {
snapshot.forEach(cookUser => {
cookUser.collection('meals').get().then(function (snapshot2) {
snapshot2.forEach(meal => {
if (meal.data().portion > 0) {
var mealObject = meal.data();
mealObject.id = meal.id;
mealObject.address = cookUser.data().address;
mealObject.cookName = cookUser.data().displayName;
mealsOnline.push(mealObject);
}
});
});
});
return Promise.all(mealsOnline);
}).catch(err => {
console.log('Error getting documents', err);
});
With the forEach() method, your cookUser object is a QueryDocumentSnapshot.
As detailed in the documentation (link above), "QueryDocumentSnapshot offers the same API surface as a DocumentSnapshot". Therefore you should use the ref abstract type of a DocumentSnapshot, as follows:
snapshot.forEach(cookUser => {
cookUser.ref.collection('meals').get().then(snapshot2 => {
.....
})
})
https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot#forEach

Resources