import * as React from "react"; import { useFormik, getIn, setIn } from "formik"; import classnames from "classnames"; import SelfServiceMessages from "./SelfServiceMessages"; export default function SelfServiceForm({ fieldsConfig, onSubmit, title, validationSchema = null, button = "Submit" }) { const [messages, setMessages] = React.useState([]); const fields = fieldsConfig.sort((a, b) => (a.position < b.position ? -1 : 1)); const formik = useFormik({ initialValues: fields.reduce((acc, field) => setIn(acc, field.name, field.value ?? ""), {}), validationSchema, onSubmit: async (values) => { if (!formik.isValid) return; setMessages([]); try { await onSubmit(values); } catch (error) { if (error.response) { const data = await error.response.json(); if (data.message) { setMessages((messages) => [...messages, { type: "error", text: data.message }]); } } else { setMessages((messages) => [...messages, { type: "error", text: error.toString() }]); } } }, }); return (
{title &&

{title}

}
{fields.map((field) => (
{formik.errors[field.name] && formik.touched[field.name] && (

{formik.errors[field.name]}

)}
))} {messages.length > 0 && }
); }