skip to Main Content

I’m using react-hook-form with typescript to send the input data to the server and create tasks. I am setting the form defaultValues as strings:

defaultValues: {
      taskType: "",
      title: "",
      start: "",
      notes: "",
      tags: "",
}

But before sending this values to the API I need to map the types so they can fit the expected ones. I am doing that with a map function. This is an example of my map function:

function formatAnyTask(formData: TaskFormInputs, taskType: TaskTypes): AnyTask {
  const { title, careRecipient } = formData;
  const start = formatDate(formData.start);
  const durationSeconds = convertMinutesToSeconds(formData.durationSeconds);
  const notes = formData.notes === "" ? null : [formData.notes];
  const tags = formData.tags === "" ? null : [formData.tags];

  return {
    taskType,
    title,
    start,
    notes,
    tags,
    durationSeconds,
    careRecipient,
  };
}

My question is: Is there a better, a recommended or a best practice way to do this rather than creating mapping functions to match the output types?

Thanks in advance!

2

Answers


  1. Have you considered using a form validation method such as Zod? I have used it and it works well even with headless UI components like antd and shadcn

    Login or Signup to reply.
  2. You can use libraries to validate the form data with the react hook forms?

    Check this link

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search