1

I am trying to read data from firestore collection to get notification token and push it to a list and pass the list to SendtoDevice function to send push notification.

I am facing issue when using foreach function and push the data getting error "for each is not a valid function"


let tokenList = [];

const userNotificationTokenDocs = await db.collection("userToken").doc(userId).get()
.then(querySnapshot => {
querySnapshot.forEach((doc) => {
console.log(doc.data().Tokens);
tokenList.push(doc.data().Tokens);
});
return null;
});

**other option which i tried, with same error.**

userNotificationTokenDocs.forEach(function(docs){
   console.log(docs.data());
   if(docs.data() != null){
    tokenList.push(docs.data().Token);
   }
});

Please help me, I am stuck with this.

2
  • You are mixing await and then in the same statement. That doesn't make any sense - just use one or the other. You might want to take a moment to review how Futures work in dart. Commented Sep 14, 2022 at 1:30
  • Thanks for the response. I tried without await still it's not pushing data to the list, and I checked twice querysnapshot it returning data. Commented Sep 14, 2022 at 2:21

1 Answer 1

1

found some BASIC mistake in your coding.

  • const userNotificationTokenDocs will always null , because you return null. forEach is void function.
  • Using await and then is unecessery. choose 1.
  • => arrow is a shorthand for { return expr; } . if you only have 1 expresion, you can shorthand with arrow. but if you have morethan 1 expression, just use bracket {} . documentation
  • userNotificationTokenDocs.forEach(function(docs){ this will error since null value cant use forEach.

I think your IDE should give you alert there's an error in your code. but you choose to run it instead fixing the error.

but is ok, keep learning code. :)

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the response. I am newbie, i am learning lot of from people like you. thanks. Could you please help me what's wrong with this. var userToken= await db.collection('Users') .doc(userId) .collection('Tokens') .get(); userToken.forEach(function(docs){ if(docs.data() != null){ TokenList.push(docs.data().Token); } });
what current error you get? did you use any additional package? because List on dart doesnt support push() method. if you want to add item to list , use add() method. tokenList.add(docs.data().Token
This is firebase cloud function, i am getting list of usertoken to send push notification, to available users based on token
Error i am getting "TypeError: forEach is not a function"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.