Home > Software design >  How to add two functions to one onClick
How to add two functions to one onClick

Time:08-20

I have two functions that need to be hung on one button. One function writes data to the Firestore, and the other writes a picture to Storage. How can I add them to the onClick on a single button?

const Header = () => {

  const submitHandler = async (e) => {
    e.preventDefault();
    try {
      await setDoc(doc(housesRef, enteredTitle), {
        title: enteredTitle,
        descr: enteredText,
        lat: enteredLatitude,
        lon: enteredLongitude,
      });
      togglePopup();
      setEnteredTitle("");
      setEnteredText("");
      setEnteredLatitude("");
      setEnteredLongitude("");
    } catch (err) {
      alert(err);
    }
  };

   const imageUpload = () => {
   const imageRef = ref(storage, `image/${uploadImage.name}`);
   uploadBytes(imageRef, uploadImage).then(() => {
   alert("Image Uploaded");
     });
   };

  return (
    <div className="header">
     ...
                  <input
                    type="submit"
                    value="Add"
                    onClick={}
                  />
     ...
   
  );
};

CodePudding user response:

Simply create a new function that calls those two different functions,

like so,

const myEncapsulatingFunc = (func1_params, func2_params) => {
  myFunc1(func1_params);
  myFunc2(func2_params);
}

Attach myEncapsulatingFunc to the onclick event and pass in the relevant parameters.

CodePudding user response:

The simple answer is you can't

You can however, just call them seperately like this:

return (
    <div className="header">
     ...
                  <input
                    type="submit"
                    value="Add"
                    onClick={() => {
                               func1();
                               func2()
                            } }
                  />
     ...
   
  );

CodePudding user response:

Why not calling imageUpload inside onSubmitHandler and just passing onSubmitHandler to the onClick?

const submitHandler = async (e) => {
    e.preventDefault();
    imageUpload()
    try {
...
    } catch (err) {
      alert(err);
    }
  };
    
<input
   type="submit"
   value="Add"
   onClick={onSubmitHandler}
 />
  • Related