Reputation: 43
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
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?
Upvotes: 1
Views: 4365
Reputation: 43
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.
Upvotes: 2