0

I'm trying to call two functions immediately one after another when user clicks a button, but I am not able to do so.

In the first function, I am calling handleChange() method in which it sets the status value using status: event.target.value

And in the second function, it should execute onSubmit() method in which I am updating the status value in DB which previously handleChange() method sets.

Here is my code snippet:

const handleChange = (event) => {
    setValues({ ...values, error: false, status: event.target.value });
};
    
console.log(status);    

const onSubmit = (event) => {
    event.preventDefault();
    setValues({ status:"", error: false, loading: true });
    console.log(status);
    updateOrderStatus(match.params.orderId, user._id, token, status).then(
      (data) => {
        if (data.error) {
          setValues({  error: data.error, success: false });
        } else {
          setValues({  status: "", success: true });
          console.log("STATUS:",status);
        }
      }
    )};

    const createOrderForm = () => {
      return (
        <button
            type="submit"
            onClick={handleChange,onSubmit}
            value="Cancelled"
            className={
              status === "Cancelled"
                ? "btn btn-primary mr-3"
                : "btn btn-outline-success mr-3"
            }
          >
            Cancelled
      )

Here are my screenshot and log files for what exactly I am trying for:

Initially
After clicking on the Cancelled button it should change the status

Victor
  • 3,669
  • 3
  • 37
  • 42
  • https://stackoverflow.com/questions/26069238/call-multiple-functions-onclick-reactjs – Ilan Frumer Jun 21 '20 at 14:59
  • Does this answer your question? [Call multiple functions onClick ReactJS](https://stackoverflow.com/questions/26069238/call-multiple-functions-onclick-reactjs) – David Jun 21 '20 at 15:00

2 Answers2

0

onClick expects a function, when you give two functions seperated by comma, it only takes the first one. Instead you give a function and execute two functions inside it. this will work

onClick={()=>{handleChange();onSubmit()}}

0

It looks like you'll need to make a higher order function that calls the two subsequent functions:

onClick={(event) => {
    handleChange(event)
    onSubmit(event)
}}

Or you could just call handleChange from inside onSubmit:

const onSubmit = (event) => {
event.preventDefault();
handleChange(event)
setValues({ status:"", error: false, loading: true });
console.log(status);
updateOrderStatus(match.params.orderId, user._id, token, status).then(
  (data) => {
    if (data.error) {
      setValues({  error: data.error, success: false });
    } else {
      setValues({  status: "", success: true });
      console.log("STATUS:",status);
    }
  }
)};

In this case you can just call onClick from your components click event:

onClick={onSubmit}

Also note that in your .then callback, you are calling to setValues here:

    setValues({  status: "", success: true });
    console.log("STATUS:",status);

When setValues is called, it will cause a re-render of the component. On that re-render, the status pulled out of values will reflect the empty string you added here: setValues({ status: "", success: true });.

However, the status in console.log("STATUS:",status) will reflect the value of status before the re-render, that being "pending".

jmealy
  • 583
  • 1
  • 5
  • 14
  • I tried this but it does not get the output I want...my status and values are coming from const [values, setValues] = useState({ error: "", status: "", success: false, }); const { status, error, success } = values; – Anuj Jain Jun 21 '20 at 15:37
  • my backend api call is : export const updateOrderStatus = (orderId, userId, token, status) => { return fetch(`${API}/order/${orderId}/status/${userId}`, { method: "PUT", headers: { Accept: "application/json", Authorization: `Bearer ${token}`, }, body: JSON.stringify(status), }) .then((response) => { return response.json(); }) .catch((err) => console.log(err)); }; – Anuj Jain Jun 21 '20 at 15:38
  • Updated my answer to address things further. Please take a look. – jmealy Jun 21 '20 at 15:54
  • Can you suggest me what should I do ? – Anuj Jain Jun 21 '20 at 16:11
  • It depends on what you're trying to do. It seems like you're trying to get some part of the response (your `data` argument) into `setValues`. Perhaps you mean to add `setValues({ status: "completed", success: true, value: data });` inside of your `else` statement in the callback. – jmealy Jun 21 '20 at 16:42