apiForm.tsx 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import {useCallback} from 'react';
  2. import {addLoadingMessage, clearIndicators} from 'sentry/actionCreators/indicator';
  3. import Form, {FormProps} from 'sentry/components/forms/form';
  4. import {t} from 'sentry/locale';
  5. import useApi from 'sentry/utils/useApi';
  6. type Props = FormProps & {
  7. apiEndpoint: string;
  8. apiMethod: string;
  9. onSubmit?: (data: Record<string, any>) => void;
  10. };
  11. function ApiForm({onSubmit, apiMethod, apiEndpoint, ...otherProps}: Props) {
  12. const api = useApi();
  13. const handleSubmit = useCallback(
  14. (
  15. data: Record<string, any>,
  16. onSuccess: (response: Record<string, any>) => void,
  17. onError: (error: any) => void
  18. ) => {
  19. onSubmit?.(data);
  20. addLoadingMessage(t('Saving changes\u2026'));
  21. api.request(apiEndpoint, {
  22. method: apiMethod,
  23. data,
  24. success: response => {
  25. clearIndicators();
  26. onSuccess(response);
  27. },
  28. error: error => {
  29. clearIndicators();
  30. onError(error);
  31. },
  32. });
  33. },
  34. [api, onSubmit, apiMethod, apiEndpoint]
  35. );
  36. return <Form onSubmit={handleSubmit} {...otherProps} />;
  37. }
  38. export default ApiForm;