Formik: Set the value of an input based on something outside of the form?

Created on 3 Nov 2017  路  6Comments  路  Source: formium/formik

I looked in the documentation, and didn't find an answer to this, so I apologize if it's covered and I missed.

Our app has some fields which are linked to each other. Imagine they look like this:

<input name="input-a" onChange={e => {props.handleChange(e); props.updateParentStuff(e)}} />
<input name="input-b" onChange={e => {props.handleChange(e); props.updateParentStuff(e)}} />

When one of the inputs is updated, the parent hits an API to get some kind of value back, and then the _other_ input needs to be updated, or vis-a-versa. So the flow looks like this:

Update input-a => pass value to parent => call api => return value => update input b
OR
Update input-b => pass value to parent => call api => return value => update input a

The issue is I can't find a way to force an input in the Formik form to have a certain value, outside of setting the initialValue parameter (we're using the render prop). I'm hacking around this problem right now by taking a state variable in the parent, and merging it with the values which get submitted when the form is. I'd like to just have the values represent the actual data to be submitted, though.

Thanks!

Most helpful comment

Probably you also want to use - https://github.com/jaredpalmer/formik#enablereinitialize-boolean, which is falseby default.

All 6 comments

Hey @kwhitaker!

I believe there is nothing wrong with initialValues being dynamic. As you can see here https://github.com/jaredpalmer/formik/blob/master/src/formik.tsx#L256, when initialValues changes and does not equal, the form is being reset with the new value.

Thanks. I'll take a look and try it again - maybe I[m missing something.

Probably you also want to use - https://github.com/jaredpalmer/formik#enablereinitialize-boolean, which is falseby default.

My suggestion is to make a class component that uses componentWillReceiveProps and pass it outside prop + whatever formik props and methods it needs. Within cWRP you can compare changes and then safely call any Formik method. Although it uses context instead of passing formik props directly, this is essentially how formik-persist works.

You can use this concept to make plugins/addons.

const SuperFormik = ({custom, ...props}) => 
  <Formik {...props} 
     render={(p) => [
       props.render(p), 
      <Persist />, 
      <CheckProfanity customThing={custom} />,
      <SomethingElse/>
     ] // imagine that these all do stuff in cWRP and cDU but render `null`
    }
  />

setFieldValue is also useful, for e.g.:
props.setFieldValue('birth_date', selectedDate);

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dearcodes picture dearcodes  路  3Comments

green-pickle picture green-pickle  路  3Comments

jaredpalmer picture jaredpalmer  路  3Comments

najisawas picture najisawas  路  3Comments

pmonty picture pmonty  路  3Comments