1

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?

6
  • I think you've got the right idea using redux-thunk, check here for a full async example: redux.js.org/docs/advanced/AsyncActions.html#-actions-js Commented Jun 2, 2016 at 21:20
  • Is your new FormData(formElement) a serialized data of your form, if yes, you would give this data instead of formElement? Commented Jun 2, 2016 at 21:29
  • If you add an onChange listener to your input, the event that's passed will have a files property that represents a FileList. Track this in your component and pass it on submit. Then in your action creator you can iterate over the file list and add each file to the FormData using append. Commented Jun 2, 2016 at 21:30
  • @MichaelRasoahaingo The form data would include files, which isn't serializable. I want to upload the files before finally submitting the form. Commented Jun 2, 2016 at 21:30
  • @Jazy48 Oh, that means you need to make two requests; one to upload the files, one to submit the rest of the form. Can't really be done in the same request. Commented Jun 2, 2016 at 21:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.