I am trying to make a collection of items. A mapped document is created on click after a user logs in, and if the user has already created a document then there are no errors. However, a new user does not yet have a document and the useEffect function is returning undefined when I look for the document. How do I create it on load for a new user?
Following error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'ingredients') I am trying to create an ingredients array.
useEffect(() => {
onAuthStateChanged(auth, (user) => {
if (user) {
const uid = auth.currentUser.uid;
const docRef = doc(db, "users", uid);
//loads the user's ingredients from firebase upon login
const getUsers = async () => {
const data = await getDoc(docRef);
if(data.data().ingredients != undefined){
setImgArr(data.data().ingredients);
}
[![Data structure][1]][1]
else {
await setDoc(docRef, {
ingredients: arrayUnion({ name: "form", image: "newImg.image" }),
});
}
};
getUsers();
} else {
//clear the ingredients array upon logout
setImgArr([]);
}
});
}, [auth]);
const clickHandler = async (e) => {
try {
setForm(e.target.value);
//get response from edamam api
const newImg = await getResponse();
//redefining uid and docRef because unable to figure out how to make them global
const uid = auth.currentUser.uid;
const docRef = doc(db, "users", uid);
//updates firebase with new ingredient
await updateDoc(docRef, {
ingredients: arrayUnion({ name: form, image: newImg.image }),
});
setImgArr([...imgArr, newImg]);
} catch (err) {
console.error(err);
}
};