简体   繁体   中英

Handling async file upload with Redux

I'm pretty new to React and Redux, and I'm having some trouble coming up with the best way to structure asynchronous file upload.

What I want is

  1. The user hits a form's submit button
  2. Files are uploaded, and the paths that they're uploaded at are returned from the server
  3. The state gets updated with those paths before a final POST request gets sent

What I'm thinking of doing now is passing the form or some higher up component into an action handler, like so

// actions.js
// using redux-thunk middleware, so this action creator
// dispatches actions on success and error events
submitForm({ formElement }) {
  return (dispatch, getState) => {
    // ... do some stuff

    fetch('/files', {
      method: 'POST',
      body: new FormData(formElement)
    })
    .then(() => dispatch(uploadSuccess()));
  }
}

Is this a bad idea? Is there a better way to get FormData than passing the form element to the action creator?

Thanks to Alex Guerra ~

Didn't realize I could simply bind an event to the file input's onChange . What I'm doing now is

render() {
  const { onChangeFiles, index } = this.props;
  return (
    // ... some other stuff, then
    <input type="file" onChange={
      (e) => {
        onChangeFiles({ files: e.target.files, index });
      }
    } />
  )
}

Then adding those files to the component's state. Then, in the final submit handler I'll POST the files in the state object before making a final post request after the upload finishes.

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