简体   繁体   English

React / Redux-在onBlur上发送多个补丁请求

[英]React / Redux - Sending multiple patch requests onBlur

I'm using Redux-form to edit guest information. 我正在使用Redux-form编辑来宾信息。 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. 我遇到的问题是,如果我使用同时编辑多个字段的Google表单,则onBlur函数也将同时发送所有请求。 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. 最终安装了redux-saga并通过排队请求解决了它。 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)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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