Redux传奇,axios和进步事件

时间:2016-11-03 13:28:42

标签: reactjs redux redux-saga

是否有干净/短/正确的方式共同使用axios承诺并上传进度事件?

假设我有下一个上传功能:

function upload(payload, onProgress) {
  const url = '/sources/upload';

  const data = new FormData();

  data.append('source', payload.file, payload.file.name);

  const config = {
    onUploadProgress: onProgress,
    withCredentials: true
  };

  return axios.post(url, data, config);
}

此函数返回了承诺。

我也有一个传奇:

function* uploadSaga(action) {
  try {
    const response = yield call(upload, payload, [?? anyProgressFunction ??]);
    yield put({ type: UPLOADING_SUCCESS, payload: response });
  } catch (err) {
    yield put({ type: UPLOADING_FAIL, payload: err });
  }
}

我希望接收进度事件并将其传递给saga。此外,我想捕获axios请求的成功(或失败)结果。有可能吗?

感谢。

1 个答案:

答案 0 :(得分:7)

所以我找到了答案,感谢Mateusz Burzyński澄清。

我们需要使用eventChannel,但有点刺激。

假设我们有上传文件的api功能:

function upload(payload, onProgress) {
  const url = '/sources/upload';

  const data = new FormData();

  data.append('source', payload.file, payload.file.name);

  const config = {
    onUploadProgress: onProgress,
    withCredentials: true
  };

  return axios.post(url, data, config);
}

在saga中,我们需要创建eventChannel,但将emit放在外面。

function createUploader(payload) {

  let emit;
  const chan = eventEmitter(emitter => {

    emit = emitter;
    return () => {}; // it's necessarily. event channel should 
                     // return unsubscribe function. In our case 
                     // it's empty function
  });

  const uploadPromise = upload(payload, (event) => {
    if (event.loaded.total === 1) {
      emit(END);
    }

    emit(event.loaded.total);
  });

  return [ uploadPromise, chan ];
}

function* watchOnProgress(chan) {
  while (true) {
    const data = yield take(chan);
    yield put({ type: 'PROGRESS', payload: data });
  }
}

function* uploadSource(action) {
  const [ uploadPromise, chan ] = createUploader(action.payload);
  yield fork(watchOnProgress, chan);

  try {
    const result = yield call(() => uploadPromise);
    put({ type: 'SUCCESS', payload: result });
  } catch (err) {
    put({ type: 'ERROR', payload: err });
  }
}