Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(types): export form body types #4

Merged
merged 1 commit into from
Mar 16, 2022

Conversation

replygirl
Copy link
Contributor

@replygirl replygirl commented Mar 13, 2022

exports SuccessBody and ErrorBody so users can cast response bodies

Motivation

I'm using formspree/formspree-react with jaredpalmer/formik. After I submit the form, I need to set any uncaught errors on the Formik:

<Formik
  ...
  onSubmit={async (values, { setErrors }) => {
    const { body } = await handleSubmit(values)
    if (body.errors)
      setErrors(
        body.errors
          .filter((x): x is Required<typeof x> => !!x.field)
          .reduce(
            (acc, cur) => ({
              ...acc,
              [cur.field]: cur.message,
            }),
            {} as Parameters<typeof setErrors>[0]
          )
      )
  }}
>

TypeScript doesn't like when you access a property of body:

Property 'errors' does not exist on type 'SubmissionBody'.
  Property 'errors' does not exist on type 'SuccessBody' (ts.2339)

Right now, you can get around this with a one-liner thanks to type-fest's UnionToIntersection...

const { errors } = (body as Partial<UnionToIntersection<typeof body>>)

...but this isn't perfect—after collapsing the union, body is no longer narrowable to SuccessBody or ErrorBody.

@colevscode
Copy link
Member

colevscode commented Mar 16, 2022

Ok! One suggestion: perhaps avoid using formspree-react with formik. Since formik has it's own state management, it seems redundant to also track error states with Formspree's useForm hook. Instead it might make sense to create a formspree client in a useEffect and call the submitForm function directly.

@colevscode colevscode merged commit b08814f into formspree:master Mar 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants