0

While running the code, I am trying to call the function addValuesForSubmission to add the row in the rows array before calling the valueSubmission function which sends the values to the database. Doing a console.log displays the value of rows and shows that the row is being added however, it is calling the valueSubmission function for submitting the values before adding the row at the end. I tried using a Promise but it is still not working.

  const valueSubmission = () => {
    //function to submit values to database
    var result = errorChecking();

    if (result.error === true) {
      setErrorMessage({ error: false, messages: [] });
      setSubmitError(true);
      setErrorMessage(result);
    } else {
      inputRef.current.focus();
      agreementpricesServices
        .updateAgreementPrices({ AgreementPrices: rows })
        .then(() => {
          setResubmit(!resubmit);
          setSuccess(true);
        })
        .catch((error) => {
          setSubmitError(true);
          setErrorMessage({
            error: true,
            messages: [error.response.error.error],
          });
          setResubmit(!resubmit);
        });
    }
  };

  const addValuesForSubmission = () => {
    //function to add last row to array before submitting values
    if (!isNaN(from) && !isNaN(price) && from !== "" && price !== "") {
      const data = {
        priceID: rows.length !== 0 ? rows[rows.length - 1].priceID + 1 : 1,
        agreementID: agreementID,
        from: from,
        to: to,
        price: price,
      };

      setRows((rows) => [...rows, data]);
      setNumberRecords(numberRecords + 1);
      setFrom("");
      setTo("");
      setPrice("");
      setID(id + 1);
    }
  };

  const submitValues = async (event) => {
    //function to submit values or to add new row in table
    event.preventDefault();

    const myPromise = new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 500);
    });

    myPromise.then(addValuesForSubmission).then(valueSubmission);
  };

0 Answers0