import { FunctionComponent, useState } from "react"; import Link from "next/link"; import { useRouter } from "next/router"; import { ErrorMessage{{#if hasManyRelations}}, Field, FieldArray{{/if}}, Formik } from "formik"; import { useMutation } from "react-query"; import { fetch, FetchError, FetchResponse } from "../../utils/dataAccess"; import { {{{ucf}}} } from '../../types/{{{ucf}}}'; interface Props { {{{lc}}}?: {{{ucf}}}; } interface SaveParams { values: {{{ucf}}}; } interface DeleteParams { id: string; } const save{{{ucf}}} = async ({ values }: SaveParams) => await fetch<{{ucf}}>(!values["@id"] ? "/{{{name}}}" : values["@id"], { method: !values["@id"] ? "POST" : "PUT", body: JSON.stringify(values), }); const delete{{{ucf}}} = async (id: string) => await fetch<{{ucf}}>(id, { method: "DELETE" }); export const Form: FunctionComponent = ({ {{{lc}}} }) => { const [, setError] = useState(null); const router = useRouter(); const saveMutation = useMutation | undefined, Error|FetchError, SaveParams>((saveParams) => save{{{ucf}}}(saveParams)); const deleteMutation = useMutation | undefined, Error|FetchError, DeleteParams>(({ id }) => delete{{{ucf}}}(id), { onSuccess: () => { router.push("/{{{lc}}}s"); }, onError: (error)=> { setError(`Error when deleting the resource: ${error}`); console.error(error); } }); const handleDelete = () => { if (!{{lc}} || !{{lc}}["@id"]) return; if (!window.confirm("Are you sure you want to delete this item?")) return; deleteMutation.mutate({ id: {{lc}}["@id"] }); }; return (

{ {{{lc}}} ? `Edit {{{ucf}}} ${ {{~lc}}['@id']}` : `Create {{{ucf}}}` }

emb['@id']) ?? [], {{else if embedded}} {{name}}: {{../lc}}["{{name}}"]?.['@id'] ?? "", {{/if}} {{/each}} } : new {{{ucf}}}() } validate={() => { const errors = {}; // add your validation logic here return errors; }} onSubmit={(values, { setSubmitting, setStatus, setErrors }) => { const isCreation = !values["@id"]; saveMutation.mutate( { values }, { onSuccess: () => { setStatus({ isValid: true, msg: `Element ${isCreation ? "created" : "updated"}.`, }); router.push("/{{{name}}}"); }, onError: (error) => { setStatus({ isValid: false, msg: `${error.message}`, }); if ("fields" in error) { setErrors(error.fields); } }, onSettled: ()=> { setSubmitting(false); } } ); }} > {({ values, status, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, }) => (
{{#each formFields}}
{{#if isRelations}}
{{name}}
(
{values.{{name}} && values.{{name}}.length > 0 ? ( values.{{name}}.map((item: any, index: number) => (
)) ) : ( )}
)} /> {{else}} {{/if}}
{{/each}} {status && status.msg && (
{status.msg}
)}
)}
Back to list { {{{lc}}} && ( )}
); };