Karim shousha
Karim shousha

Reputation: 31

How to pervent to send http request until the perious one is fulfilled?

I have a case that: when the user changes the input, with each change, I have to send an HTTP request to get some data from the server. when I get the data I update my state with new data and that, of course, affects the view. so, the problem is when the user changes the input very fast the requests don't fulfill respectively and this leads to an improper view at the end. so, I want to not send the request until the previous one is fulfilled.

const parallel = (...Promises) => {
  return Promise.all(Promises);
};

export function parentAccHandler(e, inputFiled) {
  const parentAccValue = e.target.value;
  const { fields } = this.state;
  parallel(
    getUsedRecord(fields),
    axios.get(`chartofaccounts/nextPK/${parentAccValue}`)
  )
    .then(([usedRecord, nextPkRes]) => {
      this.setState((state, props) => {
        const { fields } = state;
        fields.acc_no.value = nextPkRes.data.next_PK
          ? nextPkRes.data.next_PK
          : "";
        return {
          fields: updateOnParentAcc.call(this, fields, usedRecord, "PRESENT"),
        };
      });
    })
    .catch((err) => {
      this.setState((state, props) => {
        let { fields } = state;
        fields.acc_no.value = "";
        fields.parent_acc.prevReqStatus = "FULFILLED";
        if (parseInt(parentAccValue) === 0) {
          fields = updateOnParentAcc.call(this, fields, null, "ZERO");
        } else {
          fields = updateOnParentAcc.call(this, fields);
        }
        return {
          fields: fields,
        };
      });
    });
}

Upvotes: 1

Views: 45

Answers (1)

Flak
Flak

Reputation: 2670

Well if you wrap the input fields and other stuff into a <fieldset> and give it the disabled="disabled" attribute it will disable all fields.

When you do Axios request, add disabled="disabled" attribute to fieldset, and when request success remove that attribute.

Make it as state then just setState to that.

Other method would be to show/hide overlay/loading to prevent clicking other fields.

Upvotes: 1

Related Questions