Home > Net >  React/Firebase - OnChange event is triggered even if field not changed
React/Firebase - OnChange event is triggered even if field not changed

Time:11-25

I'm quite new so i'll try to explain as simple as i can. I have a simple form and i'm trying to update a field. In order to update i have setup the following:

  1. First get the item id of the record i want to update
  2. Update the record in firebase.

My problem is that if i change the value of one field for example "name" and submit the form, "name" is successfully updated in firebase however the other field in my case "description" is also updated with "" empty value. Same happens if "description" is changed and name is not.

export default CategoryUpdate
  const CategoryUpdate = () => {

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const params = useParams();  // get category id from url
  const [data, setData] = useState([]);

  useEffect(() => {
      const fetchData = async () => {
          const docRef = doc(db, "category", params.categoryId)
          const docSnap = await getDoc(docRef)
          if(docSnap.exists()){
              setData(docSnap.data())
          }
      };
      fetchData();
  },[params.categoryId]);

  // Updating category in Firebase
  const saveDetails = async () => {
    const updateSchool = {
        name: name,
        description: description,
    };
    try {
        const schoolRef = doc(db, "category", data.id)
        await updateDoc(schoolRef, updateSchool);
    } catch (error) {
        console.log(error);
    }
  }

  return ( 
    <form> 
      <input 
        type="text" 
        required 
        defaultValue={data.name || ''} 
        placeholder="Set a title" 
        onChange={(e) => setName(e.target.value)} 
      /> 

      <input 
        type="text" 
        required 
        defaultValue={data.description || ''} 
        placeholder="Set a title" 
        onChange={(e) => setDescription(e.target.value)} 
      /> 

      <div className='flex items-center w-full'> 
        <button type="button" 
          onClick={saveDetails}
        > 
          Edit Category 
        </button> 
      </div> 
  </form> 

  ) 
} 

export default CategoryUpdate

I tried to update a field in a form and i expected after update the updated field to be updated and the rest of the fields to keep the initial values before update.

CodePudding user response:

use the state variables in the default value

  <input 
    type="text" 
    required 
    defaultValue={name || ''} 
    placeholder="Set a title" 
    onChange={(e) => setName(e.target.value)} 
  /> 
  <input 
    type="text" 
    required 
    defaultValue={description || ''} 
    placeholder="Set a description" 
    onChange={(e) => setDescription(e.target.value)} 
  /> 

And update the state in useEffect

useEffect(() => {
   if(data){
     setDescription(data.description)
     setName(data.name)
   }
}, [data])
  • Related