I'm moving from Angular to react but I'm struggle to save some data to a collection in firestore.
The path I want to save to is : users/uid/pred
In Angular I do this and it works:
savePredictions(data: any, uid: string) {
let v: any = Object.values(data);
v.forEach((x: any[]) => {
x.forEach((match) => {
this.db
.collection("users")
.doc(uid)
.collection("pred")
.doc(match.matchday)
.set({ [match.matchId]: match }, { merge: true });
});
});
}
}
In React I do this and it fails:
const onSubmit = () => {
const userId = user?.uid;
const docRef = doc(db, "users", userId as string, "pred");
setDoc(docRef, predictions.fixtures);
console.log("SUBMIT TO FIREBASE:", predictions.fixtures);
};
Authentication is working and I can receive data from the database, also I have data in my predictions.fixtures to send, it is an array.
Can anyone show me code had to save to this collection called 'pred'?
CodePudding user response:
I had to use the setDoc with doc, which creates a new doc with collection. I had to run it in a forEach loop because my data is an array so each iteration has to be setDoc BUT because the name of the doc changes:
"gameweek" String(index 1)
it creates a new doc, thus making my saved data in different docs and nicer to view in firestore database.
const onSubmit = () => {
setShowSave(false);
const userId = user?.uid;
predictions.fixtures[0].forEach((el: any, index: number) => {
setDoc(doc(db, "users", userId as string, "predx", "gameweek" String(index 1)), {
["gameweek" String(index 1)]: el,
});
});
};
CodePudding user response:
there is three possible reasons.
->version difference - you are using version 8 in angular while version 9 in react.and all most many syntax changes in firebase 8 to 9
-> your collection name should be in string format (prediction.fixtures).
-> you have to give value of your fields in your setDoc. the syntax of setDoc is setDoc(db , "collection-name" , field-value).