Formik: ❓2 mode (Create/Edit) in one form (same fields, rules with different onSubmit calls)

Created on 10 Dec 2019  ·  4Comments  ·  Source: formium/formik

❓Question with an example

Hello ! is it possible to use a single form for Create/Edit ? meaning they have the same fields and rules, but the onSubmit is different depending on the usecase.

here is my try and it's not working : https://gist.github.com/kevbarns/850e1f96129e626a3141b803583b06d7

Current behavior :

EDIT :
IF url has an id, the useEffect will run and fill the form with the correct values, set Formik onSubmit prop and form onSubmit prop with the correct handler, Formik enableReinitialize to true.

CREATE :
IF no url, empty form and set Formik onSubmit prop and form onSubmit with the correct handler prop, Formik enableReinitialize to false.

Issue

  • Edit : the form gets emptied and saved with empty values in the DB
  • Create : does not work.

—> in both case, all values gets added to the URL...

in any case,
Thanks !

Most helpful comment

should not be <form onSubmit={props.handleSubmit}> ? you should use the handleSubmit from the formik bag

All 4 comments

I guess you can always check either if there is an id or something in the route, or pass some property through a route in router (reach/router, react/router) to let the component know in which context it should work.

should not be <form onSubmit={props.handleSubmit}> ? you should use the handleSubmit from the formik bag

Specifically what the previous comment said, it's this line: https://gist.github.com/kevbarns/850e1f96129e626a3141b803583b06d7#file-productform-js-L263

Should be

<form onSubmit={props.handleSubmit}>

instead.

It's correct ! thanks guys.

Was this page helpful?
0 / 5 - 0 ratings