Last active
January 22, 2018 09:23
-
-
Save JoaoCnh/275c7e6d2883509d425ea8798acc06c9 to your computer and use it in GitHub Desktop.
Ajax Form Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import PropTypes from "prop-types"; | |
class AjaxForm extends React.Component { | |
static propTypes = { | |
type: PropTypes.string.isRequired, | |
url: PropTypes.string.isRequired, | |
onSuccess: PropTypes.func.isRequired, | |
}; | |
static defaultProps = { | |
type: "POST", | |
}; | |
state = { | |
error: false, | |
}; | |
_sendRequest = async (values, { setSubmitting }) => { | |
// here you can process values however you wish | |
const { url, fields, type, onSuccess } = this.props; | |
try { | |
const formData = new FormData(); | |
for (let field of fields) { | |
formData.append(field, values[field]); | |
} | |
const res = await fetch(url, { method: type, body: formData }); | |
const json = await res.json(); | |
setSubmitting(false); | |
onSuccess(json); | |
} catch (error) { | |
setSubmitting(false); | |
this.setState({ error: error.message }); | |
} | |
}; | |
render() { | |
const { render } = this.props; | |
return render({ | |
...this.state, | |
sendRequest: this._sendRequest, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment