简体   繁体   中英

React / Redux - Sending multiple patch requests onBlur

I'm using Redux-form to edit guest information. When leaving a field, the content of the field is patched to the guest with a simple patch request and the store is updated. The problem I have is that if I use Google forms which edit multiple fields at the same time, the onBlur function sends all requests at the same time as well. This triggers the error:

Unhandled Rejection (Error): Guest is already patching

How can I make it so guests can be updated in parallel?

export function patchGuest(guest) {
  return (dispatch, getState) => {
    if (shouldPatchGuest(getState())) {
      dispatch(apiPatchGuest());
      return BookingApi.patchGuest(guest.id, guest.json())
        .then(response => {
          const json = response.data;
          const updatedGuest = Guest.asGuest(json);
          dispatch(setStateUpdateGuest(updatedGuest));
        })
        .catch(err => {
          dispatch(apiError(err));
          throw err;
        });
    }
    return Promise.reject(new Error('Guest is already patching'));
  };
}

-

patchOnBlur = (event) => {
    const { meta: { dirty, error }, dispatch, currentGuest, fieldName } = this.props;
    if (dirty && !error) {
      const patched = currentGuest.patch({
        [fieldName]: event.target.value
      });
      dispatch(patchGuest(patched));
    }
  };

Thanks in advance.

Ended up installing redux-saga and solved it by queueing up the requests. Feel free to correct this or come with improvements. This is by no means finished code.

function* patchGuest(action) {
  const dataToPatch = {
    action.fieldName: action.fieldValue,
  }
  try {
    yield call(
      Api.patchGuest, 
      action.id,
      dataToPatch
    );
    yield put({ 
      type: "BOOKING_SET_STATE_UPDATE_GUEST",
      id: action.id, 
      fieldName: action.fieldName, 
      fieldValue: action.fieldValue 
    });
  } catch (e) {
    // yield put({ type: "GUEST_PATCH_FAILED", message: e.message });
  }
}

function* watchPatchGuest() {
  const requestChan = yield actionChannel('SAGA_BOOKING_API_PATCH')
  while (true) {
    const payload = yield take (requestChan);
    yield call(patchGuest, payload)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM