Skip to content

Instantly share code, notes, and snippets.

@JoaoCnh
Last active January 22, 2018 09:23
Show Gist options
  • Save JoaoCnh/275c7e6d2883509d425ea8798acc06c9 to your computer and use it in GitHub Desktop.
Save JoaoCnh/275c7e6d2883509d425ea8798acc06c9 to your computer and use it in GitHub Desktop.
Ajax Form Component
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