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
- The user hits a form's submit button
- Files are uploaded, and the paths that they're uploaded at are returned from the server
- 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?
onChangelistener to your input, the event that's passed will have afilesproperty 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.