How to “yield put” in redux-saga within a callback?

前端 未结 3 1102
猫巷女王i
猫巷女王i 2020-12-30 23:56

Because \"yield\"-statement isn\'t allowed within a callback, how can i use the \"put\" feature of redux-saga within a callback?

I\'d like to have the following call

3条回答
  •  有刺的猬
    2020-12-31 00:23

    I got myself into a similar situation this week.

    My solution was to call a dispatch inside the callback and pass the result.

    I was handling file uploads so wanted to do a readAsArrayBuffer() call, initially in my saga something like this:

    function* uploadImageAttempt(action) {
      const reader = new FileReader();
    
      reader.addEventListener('loadend', (e) => {
        const loadedImage = reader.result;
        yield put(Actions.uploadImage(loadedImage)); // this errors, yield is not allowed
      });
    
      reader.readAsArrayBuffer(this.refs[fieldName].files[0]);
    }
    

    How I got round this was by doing the readAsArrayBuffer() in my component, then call a connected dispatch function:

    // in my file-uploader component
    handleFileUpload(e, fieldName) {
      e.preventDefault();
    
      const reader = new FileReader();
    
      reader.addEventListener('loadend', (e) => {
        const loadedImage = reader.result;
        this.props.uploadFile(
          this.constructDataObject(),
          this.refs[fieldName].files[0],
          loadedImage
        );
      });
    
      reader.readAsArrayBuffer(this.refs[fieldName].files[0]);
    
    }
    
    ...
    
    const mapDispatchToProps = (dispatch) => {
      return {
        uploadFile: (data, file, loadedImage) => {
          dispatch(Actions.uploadFile(data, file, loadedImage))
        }
      }
    }
    

    Hope that helps

提交回复
热议问题