1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00

Add Update Formik Initial Values When Props Change as a react til

This commit is contained in:
jbranchaud
2019-07-31 08:33:08 -05:00
parent 5887c9a430
commit 3279cf3fc3
2 changed files with 46 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/).
_828 TILs and counting..._
_829 TILs and counting..._
---
@@ -567,6 +567,7 @@ _828 TILs and counting..._
- [Spelunking Through Components With Enzyme's Dive](react/spelunking-through-components-with-enzymes-dive.md)
- [Sync Your react-router State With Redux](react/sync-your-react-router-state-with-redux.md)
- [Test Files In create-react-app](react/test-files-in-create-react-app.md)
- [Update Formik Initial Values When Props Change](react/update-formik-initial-values-when-props-change.md)
- [Upgrading To The Latest React In CodeSandbox](react/upgrading-to-the-latest-react-in-codesandbox.md)
- [Use A Ref To Autofocus An Input](react/use-a-ref-to-autofocus-an-input.md)
- [Use React 16 With Gatsby](react/use-react-16-with-gatsby.md)

View File

@@ -0,0 +1,44 @@
# Update Formik Initial Values When Props Change
When a [Formik](https://jaredpalmer.com/formik/) form mounts, whatever the
initial values are set to is what they will be. Even if the initial values are
computed from props, those props changing will not affect `initialValues` after
mount.
```javascript
const ZipForm = ({ currentZip }) => {
return (
<Formik
initialValues={{ zip: currentZip }}
onSubmit={(values, actions) => {
// do stuff
}}
...
```
If we are fetching the user's saved zip code asynchronously from a server while
the form is first being rendered, then `currentZip` will start as an empty
value. Once the async request comes back and `currentZip` is set, we won't see
the form update the `zip` field.
There was a time when you would have to jump through some hoops to make sure
the freshest prop value made it into the form. Now, Formik provides a handier
mechanism -- the `enableReinitialize` prop.
```javascript
const ZipForm = ({ currentZip }) => {
return (
<Formik
initialValues={{ zip: currentZip }
enableReinitialize
onSubmit={(values, actions) => {
// do stuff
}}
...
```
By setting `enableReinitialize` to true, we are telling Formik that any prop
changes that flow into the `initialValues` object should cause those values to
be _reinitialized_.
See a [live example](https://codesandbox.io/s/sad-mendeleev-4dbbp).