Skip to content

Error management

Norbert Schuler edited this page Dec 12, 2020 · 1 revision

I have added a function that will help us to show form errors coming from the server in our forms directly.

export default function addServerErrors<T>(
    errors: { [P in keyof T]?: any },
    setError: (
      fieldName: keyof T,
      error: { type: string; message: string }
    ) => void
  ) {
    return Object.keys(errors).forEach((key) => {      
      if(errors[key as keyof T] && errors[key as keyof T].errors){
        setError(key as keyof T, {
          type: "server",
          message: errors[key as keyof T].errors!.join(". "),
        });
      }
    });
  }

Usage - For eg:

errors = {
    "name":{},
    "slug":{"errors":["project.slug.already_exists"]},
}
addServerErrors(errors, setError);

The setError function comes from the react hook forms, where it will add errors if the name of the field matches with the name of the field returned from the server. VERY IMPORTANT - we have to match the name of the fields with the server

Clone this wiki locally