Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik FieldArray not rerendering on updated values even with enableReinitialize

Tags:

reactjs

formik

Formik enableReinitialize documentation

Default is false. Control whether Formik should reset the form if initialValues changes (using deep equality).

I'm passing in an object (through props) that I set in initialValues, the object definition is:

{
  "shoppingList": {
    "title": "",
    "items": [ { "quantity": 0, description: "" } ]
  }
}

I'm using this in a Formik FieldArray component. I'm updating the quantity in a button onClick handler using an inline arrow function that directly mutates the item via current element param in items.#map callback.

Formik is not rerendering the form to reflect the updated quantity. Formik knows about the quantity as when I submit the form the component storing quantity is rerendered to the correct updated quantity.

like image 591
Gibrahh Avatar asked Mar 04 '23 09:03

Gibrahh


1 Answers

Fixed by using arrayHelpers.#replace instead of directly updating the items.
arrayHelpers documentation

The answer is deep equality is value based. I'm unsure whether the term deep equality is ever valid in respect to reference based equality, but my confusion led to me asking that way anyway.

Either directly mutating the data in an item object in the array or immutably updating works as expected in this case. Unsure whether this would be different if the data I was updating was not primitive - still fairly new to the wonderfully scary world of JS.

In this case also works with enableReinitialize or without.

Full working example here, both mutating and immutable update logic used (one for minus quantity, other for plus quantity): https://codesandbox.io/s/k2wzk9q605?fontsize=14

like image 138
Gibrahh Avatar answered May 05 '23 07:05

Gibrahh