Skip to content
Advertisement

Change only one specific value from dynamic input field

i need some help.

So i have:

 data.map( (doc) => { 
      return (
         <div>
             <div> {doc.name}</div>
             <div> {doc.age}</div>
         </div>
   )
})

This iterate some data from Firebase Firestore into the web page.

Then there’s an input field to change the age.

const [age, setAge] = useState(1);

const handleSubmitAge = async () => {
   const ageRef = doc(db, "user", "docID")
   await updateDoc(ageRef, {
         age : age
     });
}

.....

<div>
     <TextField
        value={age}
        onChange={ e => setAge(e.target.value)}
     />
     <Button onChange={handleSubmitAge}>
        Submit Age
     </Button>
</div

If i want to change doc.age, how do i do that? If i just write it like above, then if there are 10 names, all names will have the same age.

How do i make a reference to the “docID” in that “age” input field so that only one specific age is updated one specific person (name)?

Advertisement

Answer

Solution:

Thank you Mr. Frank van Puffelen.

Firstly, i need to access the document id for each doc in data.map( (doc) => … ). We can do that earlier when we fetch the data from Firestore

async () => {
            const q = query(collection(db, "collectionName"), where("category", "==", `${some condition here}`));
            const querySnapshot = await getDocs(q);
                querySnapshot.forEach((doc) => {
                setData(querySnapshot.docs.map((doc) => ({...doc.data(), id:doc.id})))
                })
        };

That id:doc.id is what gives us the document id. Also thank you for the youtube tutorial from PedroTech and Maksim Ivanov for showing how to get this document id.

Advertisement