apiForm.tsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import {Component} from 'react';
  2. import {addLoadingMessage, clearIndicators} from 'sentry/actionCreators/indicator';
  3. import {Client} from 'sentry/api';
  4. import Form from 'sentry/components/forms/form';
  5. import {t} from 'sentry/locale';
  6. type Props = Form['props'] & {
  7. apiEndpoint: string;
  8. apiMethod: string;
  9. onSubmit?: (data: Record<string, any>) => void;
  10. };
  11. export default class ApiForm extends Component<Props> {
  12. componentWillUnmount() {
  13. this.api.clear();
  14. }
  15. api: Client = new Client();
  16. onSubmit = (
  17. data: Record<string, any>,
  18. onSuccess: (response: Record<string, any>) => void,
  19. onError: (error: any) => void
  20. ) => {
  21. this.props.onSubmit && this.props.onSubmit(data);
  22. addLoadingMessage(t('Saving changes\u2026'));
  23. this.api.request(this.props.apiEndpoint, {
  24. method: this.props.apiMethod,
  25. data,
  26. success: response => {
  27. clearIndicators();
  28. onSuccess(response);
  29. },
  30. error: error => {
  31. clearIndicators();
  32. onError(error);
  33. },
  34. });
  35. };
  36. render() {
  37. const {
  38. onSubmit: _onSubmit,
  39. apiMethod: _apiMethod,
  40. apiEndpoint: _apiEndpoint,
  41. ...otherProps
  42. } = this.props;
  43. return <Form onSubmit={this.onSubmit} {...otherProps} />;
  44. }
  45. }