You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ValidationForm.tsx 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2019 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. import * as React from 'react';
  21. import { FormikActions, FormikProps, Formik } from 'formik';
  22. export type ChildrenProps<V> = T.Omit<FormikProps<V>, 'handleSubmit'>;
  23. interface Props<V> {
  24. children: (props: ChildrenProps<V>) => React.ReactNode;
  25. initialValues: V;
  26. isInitialValid?: boolean;
  27. onSubmit: (data: V) => Promise<void>;
  28. validate: (data: V) => { [P in keyof V]?: string } | Promise<{ [P in keyof V]?: string }>;
  29. }
  30. export default class ValidationForm<V> extends React.Component<Props<V>> {
  31. mounted = false;
  32. componentDidMount() {
  33. this.mounted = true;
  34. }
  35. componentWillUnmount() {
  36. this.mounted = false;
  37. }
  38. handleSubmit = (data: V, { setSubmitting }: FormikActions<V>) => {
  39. const result = this.props.onSubmit(data);
  40. const stopSubmitting = () => {
  41. if (this.mounted) {
  42. setSubmitting(false);
  43. }
  44. };
  45. if (result) {
  46. result.then(stopSubmitting, stopSubmitting);
  47. } else {
  48. stopSubmitting();
  49. }
  50. };
  51. render() {
  52. return (
  53. <Formik<V>
  54. initialValues={this.props.initialValues}
  55. isInitialValid={this.props.isInitialValid}
  56. onSubmit={this.handleSubmit}
  57. validate={this.props.validate}>
  58. {({ handleSubmit, ...props }) => (
  59. <form onSubmit={handleSubmit}>{this.props.children(props)}</form>
  60. )}
  61. </Formik>
  62. );
  63. }
  64. }