Home > Software design >  Two Functions in onSubmit (React)
Two Functions in onSubmit (React)

Time:12-01

I'm trying to figure out how I can trigger two functions within an onSubmit event handler inside a form element in React. I've been googling for answers, but they either have () after the functions (which returns an error), only one function works, or neither of two works.

Here are my functional components

const [checkBox, setCheckBox] = useState(false)
const [formData, setFormData] = useState(initialStateForm)
//initialStateForm is an object of user inputs

Here is the form element

<form className="restaurant" onSubmit={(handleSubmit, handleSubmitVisit)}>
//I tried (handleSubmitVisit && handleSubmit) but only one fires

This one is a handleSubmit function with conditional statements

    } if (formData.rating === "") {
        rate = 0
        rateArray = []
        countRate = 0
    } else if (formData.rating !== "") {
        rate = parseFloat(formData.rating)
        rateArray = [parseInt(formData.rating)]
        countRate = 1
    }
    return fetch('http://localhost:4000/restaurants', {
        method: "POST",
        headers: {
            "Content-Type" : "application/json"
        },
        body: JSON.stringify({
            ...formData,
            location: parseFloat(formData.location),
            rating: rate,
            ratingData: rateArray,
            ratingcount: countRate,
            comment: ""
        })
    })

And this one should execute when user clicks on a checkbox

   if (checkBox) {
        fetch('http://localhost:4000/user', {
            method: "POST",
            headers: {
                "Content-Type" : "application/json"
            },
            body: JSON.stringify({
                ...formData,
                location: parseFloat(formData.location),
                rating: parseInt(formData.rating),
                ratingData: [parseInt(formData.rating)],
                ratingcount: 1,
                comment: "",
                userrating: parseInt(formData.rating),
                visitCounter: parseInt(1),
                id: restaurant.length   1
                })
            })
        }

Appreciate the help!

CodePudding user response:

You can create a new function that runs both functions.

Simple example below:

const handleSubmit = () => {
  console.log('running handlesubmit function')
};

const handleSubmitVisit = () => {
  console.log('running handlesubmitVisit function')
};

const runBothFunctions = () => {
  handleSubmit();
  handleSubmitVisit();
};

runBothFunctions();

Also, feel free to add conditions to your new function. In your case, maybe something like:

const runBothFunctions = () => {
  if ( /*some condition*/ ) {
    //run handleSubmit function
    handleSubmit();
  } else if (checkbox) {
    //run handle handleSubmitVisit function
    handleSubmitVisit();
  } else {
    /*something else*/
  }
};

Then call your new function on your form:

<form className="restaurant" onSubmit={runBothFunctions}>

CodePudding user response:

Here is a quick fix

<form 
  className="restaurant" 
  onSubmit={(values) => {
      handleSubmit(values)
      handleSubmitVisit(values)
  }

if you want the function to be called in sequence

<form 
  className="restaurant" 
  onSubmit={async (values) => {
      await handleSubmit(values)
      await handleSubmitVisit(values)
  }

But what happens in cases where one of the api call fails, I think if you have control over the api, it better to handle it one api call, so transactions can be handled by the backend

Hope it helps

CodePudding user response:

You have 4 different options to do it.

  1. Write the 2 functions inside a []:
<form className="restaurant" onSubmit={() => [handleSubmit(), handleSubmitVisit()]}>
  1. Run one of the functions at the beginning of the other:
const handleSubmit = () => {
  handleSubmitVisit();
  // Rest of the code
}
  1. Run another function that runs the two functions and then use it in onSubmit:
const runFunctions = () => {
  handleSubmit();
  handleSubmitVisit();
};
<form className="restaurant" onSubmit={runFunctions}>
  1. (Simillar to 3) Write an arrow function and then call the 2 functions inside that:
<form className="restaurant" onSubmit={() => {
  handleSubmit();
  handleSubmitVisit();
}}>
  • Related