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

{book ? `Edit Book ${book["@id"]}` : `Create Book`}

{ 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("/books"); }, 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, }) => (
reviews
(
{values.reviews && values.reviews.length > 0 ? ( values.reviews.map((item: any, index: number) => (
)) ) : ( )}
)} />
{status && status.msg && (
{status.msg}
)}
)}
{book && ( )}
); };