Skip to content

Commit

Permalink
Handle form errors (#270)
Browse files Browse the repository at this point in the history
* removed useless import in Show

* display api error for each fields

* refacto with reduce

* reverted ReferenceLinks import suppression

* removed useless SubmissionError class, set errors Formik compatible in dataAccess.ts

* tests passed

* simplified errors

* added ErrorMessage component

* set default msg

* typed Violation
  • Loading branch information
justinezahiri committed Mar 15, 2021
1 parent 8b60676 commit 93403c8
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 41 deletions.
6 changes: 0 additions & 6 deletions src/generators/NextGenerator.js
Expand Up @@ -13,9 +13,6 @@ export default class NextGenerator extends BaseGenerator {
"components/foo/Show.tsx",
"components/foo/Form.tsx",

// interfaces
"error/SubmissionError.ts",

// types
"types/Collection.ts",
"types/foo.ts",
Expand Down Expand Up @@ -92,9 +89,6 @@ export default class NextGenerator extends BaseGenerator {
// components
"components/common/ReferenceLinks.tsx",

// error
"error/SubmissionError.ts",

// types
"types/Collection.ts",

Expand Down
1 change: 0 additions & 1 deletion src/generators/NextGenerator.test.js
Expand Up @@ -44,7 +44,6 @@ describe("generate", () => {
"/components/abc/Show.tsx",
"/components/abc/Form.tsx",
"/components/common/ReferenceLinks.tsx",
"/error/SubmissionError.ts",
"/types/Abc.ts",
"/types/Collection.ts",
"/pages/abcs/[id]/index.tsx",
Expand Down
21 changes: 10 additions & 11 deletions templates/next/components/foo/Form.tsx
Expand Up @@ -2,7 +2,7 @@ import { FunctionComponent, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import Head from "next/head";
import { Formik } from "formik";
import { ErrorMessage, Formik } from "formik";
import { fetch } from "../../utils/dataAccess";
import { {{{ucf}}} } from '../../types/{{{ucf}}}';

Expand All @@ -21,7 +21,7 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
await fetch({{{lc}}}['@id'], { method: "DELETE" });
router.push("/{{{name}}}");
} catch (error) {
setError("Error when deleting the resource.");
setError(`Error when deleting the resource: ${error}`);
console.error(error);
}
};
Expand All @@ -42,7 +42,7 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
// add your validation logic here
return errors;
}}
onSubmit={async (values, { setSubmitting, setStatus }) => {
onSubmit={async (values, { setSubmitting, setStatus, setErrors }) => {
const isCreation = !values["@id"];
try {
await fetch(isCreation ? "/{{{name}}}" : values["@id"], {
Expand All @@ -57,8 +57,9 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
} catch (error) {
setStatus({
isValid: false,
msg: `Error when ${isCreation ? 'creating': 'updating'} the resource.`,
msg: `${error.defaultErrorMsg}`,
});
setErrors(error.fields);
}
setSubmitting(false);
}}
Expand Down Expand Up @@ -91,7 +92,11 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
onBlur={handleBlur}
/>
</div>
{ errors.{{name}} && touched.{{name}} && <div className="invalid-feedback">{ errors.{{name}} }</div> }
<ErrorMessage
className="text-danger"
component="div"
name="{{name}}"
/>
{{/each}}

{status && status.msg && (
Expand All @@ -105,12 +110,6 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
</div>
)}

{error && (
<div className="alert alert-danger" role="alert">
{error}
</div>
)}

<button
type="submit"
className="btn btn-success"
Expand Down
16 changes: 0 additions & 16 deletions templates/next/error/SubmissionError.ts

This file was deleted.

13 changes: 6 additions & 7 deletions templates/next/utils/dataAccess.ts
Expand Up @@ -3,7 +3,6 @@ import has from "lodash/has";
import mapValues from "lodash/mapValues";
import isomorphicFetch from "isomorphic-unfetch";
import { ENTRYPOINT } from "../config/entrypoint";
import { SubmissionError, SubmissionErrorList } from "../error/SubmissionError";

const MIME_TYPE = "application/ld+json";

Expand All @@ -29,16 +28,16 @@ export const fetch = async (id: string, init: RequestInit = {}) => {
const json = await resp.json();
if (resp.ok) return normalize(json);

const error = json["{{{hydraPrefix}}}description"] || resp.statusText;
if (!json.violations) throw Error(error);

const errors: SubmissionErrorList = { _error: error };
const defaultErrorMsg = json["hydra:title"];
const status = json["hydra:description"] || resp.statusText;
if (!json.violations) throw Error(defaultErrorMsg);
const fields = {};
json.violations.map(
(violation: Violation) =>
(errors[violation.propertyPath] = violation.message)
(fields[violation.propertyPath] = violation.message)
);

throw new SubmissionError(errors);
throw { defaultErrorMsg, status, fields };
};

export const normalize = (data: any) => {
Expand Down

0 comments on commit 93403c8

Please sign in to comment.