'REACT JS FIREBASE FIRESTORE- how can i update my field in a document?

here is my manageexam.jsx file this is where the update happen when i click the manage button on the table. i want to update a specific document id (3BelYq7lMxRNrWKknCRK- this is a sample of my document id but ofcourse there will be a lot of document id when i will add more inside the collection.) but i want to update the fields without manually adding the document Id that i want to update.

const ManageExam = () => {

  const [description,setDesc]=useState("")
  const [title,setTitle]=useState("")


  
  function handleUpdate(e){
    e.preventDefault();
    
    const examcollref = doc(db,'Exams' "3BelYq7lMxRNrWKknCRK")
    updateDoc(examcollref,{
      title:title,
      description:description
    } ).then(response => {
      alert("updated")
    }).catch(error =>{
      console.log(error.message)
    })
   
  } 

  return (
    <div className="manageExam">
      <Sidebar/>
    <div className="manageExamContainer">
       
        
        <div className="examInfo">
        <h1>Manage Exam</h1>
        </div>
        <div className="left">
          <div className="leftForm">
          <div className="leftTitle">
            Exam information
          </div>
          <br />
          <div className="leftTitle">
            
          </div>
         
            <form  onSubmit={handleUpdate}>
            <label >Exam Title</label>
              <input 
              type="text" 
              placeholder={title.doc}
              value={title}
              onChange={e => setTitle(e.target.value)}/> 
            <label htmlFor="">Description</label>
          <textarea 
            id="desc"
            cols="30" 
            rows="7"
            value={description}
            onChange={e =>setDesc(e.target.value)}
            ></textarea>
            



            <button type="submit">Update</button>
            </form>

          </div>
               

          </div>
            <div className="right">
           <div className="rightForm">
           <div className="rightTitle">
            Add Questions
            <Link to= {`add_question`}style={{textDecoration:"none"}} className="link" >
                  Add new
              </Link>
          </div>
          <div className="rightContainer">
            {/* <p>1. What is the Meaning of db?</p> */}
         {/* <div>
           <input type="radio" name="option1" value="database" checked/>
           <label htmlFor="">database</label>
         </div>
         <div>
           <input type="radio" name="option2" value="data" disabled/>
           <label htmlFor="">data</label>
         </div>
         <div>
           <input type="radio" name="option3" value="databytes" disabled/>
           <label htmlFor="">databytes</label>
         </div>
         <div>
           <input type="radio" name="option4" value="databoard" disabled/>
           <label htmlFor="">databoard</label>
         </div>
         <br />
         <button>update</button>
         <button>delete</button> */}

          </div>

          
           </div>

            </div>
    </div>
</div>
  )
}

export default ManageExam

export const Examtable = ({id}) => {

    const [list,setExamlist] = useState([])

    // function to call the list from the firestore
  useEffect (()=>{
    const unsub = onSnapshot(
      collection(db, "Exams"), //"exams -> pangalan ng database/("collection") ko"
      (snapShot) => {
        let list = [];
        snapShot.docs.forEach((doc) => {
          list.push({ id: doc.id, ...doc.data() });
        });
        setExamlist(list);
        console.log(list.id);
      },
      (error) => {
        console.log(error);
      }
    );

    return () => {
      unsub();
    };
  },[]);
  const handleDelete = async (id) => {
    alert("Do you want to delete?")
    //window.confirm("Are you sure you want to delete?");
    try {
      await deleteDoc(doc(db, "Exams", id));
      setExamlist(list.filter((item) => item.id !== id));
      console.log(id)
    } catch (err) {
      console.log(err);
    }
    
  };

 
  const actionColumn = [{field: "action", headerName: "Action", width: 200, renderCell:(params)=>{
        return(
            <div className="cellAction">
                <div className="manageButton"> {/*/exam/manage_exam*/}
                  <Link to={`/exam/manage_exam/${params.row.id}`} style={{textDecoration:"none"}} className="link" >
                    Manage
                </Link>
                

                </div>
                <div className="deleteButton"  onClick={() => handleDelete(params.row.id)}>Delete</div>
            </div>
        )
    }}];
    return (
        <div className="examtable" >
            <div className="examtableTitle">
                Exam
                <Link to="/exam/new_exam/" style={{textDecoration:"none"}} className="link">
                    Add new
                </Link>
            </div>
         <DataGrid
        className="datagrid"
        
            rows={list} //eto mga list nung nasa firebase
          columns={examColumns.concat(actionColumn)}
          pageSize={9}
          rowsPerPageOptions={[9]}
          checkboxSelection
        /> 
        
      </div>
    )
}

export default Examtable

here is the examtable.jsx where all the document in the collection will be displayed. when i click the manage button, the url will display like this (localhost:3000/exam/manageexam/3BelYq7lMxRNrWKknCRK,, its because i click on this document but i cant update it at all because the console always said the id was undefined. i hope you understand what im saying



Solution 1:[1]

Because your pass id with Link in Examtable file.I think u must use useParams from react-router-dom in ur ManageExam.

First you need add id in your route path file, like this.

path: '/exam/manageexam/:id'

And then, in ur ManageExam.

import {useParams} from 'react-router-dom'

const ManageExam = () => {

 const {id} = useParams()
  const [description,setDesc]=useState("")
  const [title,setTitle]=useState("")


  
  function handleUpdate(e){
    e.preventDefault();
    
    const examcollref = doc(db,'Exams', id)
    updateDoc(examcollref,{
      title:title,
      description:description
    } ).then(response => {
      alert("updated")
    }).catch(error =>{
      console.log(error.message)
    })
   
  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gieyudh