Formik: Why is typeof initialValues just Values not Partial<Values> in TypeScript?

Created on 26 Oct 2019  路  3Comments  路  Source: formium/formik

鉂換uestion

I'm not sure it's intended or just missed.
If it is intended, I guess that the goal is forcing programmers to give any value to each field explicitly(while formik works well with unintialized values).
But I think it's hard to do sometimes.

Let's assume that you're writing a Formik form that sends a message to another user.

Its Values could look like

interface Message {
  to: string // maybe an ID of an user
  body: string 
}

<Formik<Message> initialValues={{ to: "", body: ""}}>

to in Message should inhabit a value when the form is submitted,
however, it can't be initialized with a value every time.
Imagine, there is a select box in the formik render component, and the select box will determine the value of to(the ID of message receiver).
Sometimes you can specify the receiver showing the form, but sometimes you don't.
But making to to to? or nullable is not the best option. Because it should not be null or undefined when it is submitted.

Most helpful comment

Yes, because touched is not constructed unless a field is present in values.

1850

Understandable, it is an implementation detail and not quite the ideal. I do think custom fields should be able to initialize their own default values, such that initialValues wouldn't be necessary at all and only needed when values are known ahead of time. But it is incompatible with the current API, so would have to wait for a large rewrite, maybe v3.

All 3 comments

I don't understand it either. I think it's intended because the docs says:

Even if your form is empty by default, you must initialize all fields with initial values otherwise React will throw an error saying that you have changed an input from uncontrolled to controlled.

But this is true only for native form elements. Custom fields can handle their values before rendering and can transform undefined to an empty string (for example) if it's necessary. Also, custom fields can be created without native form elements so this error won't be thrown even with undefined.

Is there another reason why initialValues are not Partial?

Yes, because touched is not constructed unless a field is present in values.

1850

Understandable, it is an implementation detail and not quite the ideal. I do think custom fields should be able to initialize their own default values, such that initialValues wouldn't be necessary at all and only needed when values are known ahead of time. But it is incompatible with the current API, so would have to wait for a large rewrite, maybe v3.

Thanks for info! It makes sense now. Hopefully, it will be improved in the future.

Was this page helpful?
0 / 5 - 0 ratings