0
votes

In my react component I have these two initial values

 const [initialValues, setInitialValues] = useState({
    name: 'Tom',
    age: 85,
  });

And I have a text field to change the values for the name field. And I have a button to change the age field.

If I type name as 'Jerry' and press that button to update the age It will update the age to 75 and reset the name 'Jerry' to 'Tom' again.

This is my code

Type Jerry in the text box and hit the button to see that it changes to the "Tom"

How do I fix this?

Anyhelp! Thanks in advance! =)

1
The name is reset to 'Tom' again because of line 26: setInitialValues({ ...initialValues, age: 75 });. The initialValues is { name: 'Tom', age: 85 }, so you're using the spread(...) operator to spread the initialValues, overwriting only the age property, whilst the name property stays as 'Tom'.Kapobajza
@Kapobajza How can I fix this?Pathum Kalhan
I am not quite sure what you are trying to achieve? You want to submit the form and the value of the input field should be the same as the one you submitted?Kapobajza
I have initial values, whiling the user entering some fields I want to update some of the initial values using an API call. @KapobajzaPathum Kalhan
Try this: just change the line 26 from setInitialValues({ ...initialValues, age: 75 }); to: setInitialValues({ name: /* get the value of the name text field */, age: 75 });Kapobajza

1 Answers

0
votes

You cannot reset form values like that to initial values.

What you need to do is to use method resetForm() from Formik form ref.

You provide only once what are initial values, and reset when ever you need to.

I forked your codesanbox and modified code. https://codesandbox.io/s/formik-re-render-initialvalues-forked-i84sy

Here are parts of the code related to what you need to do

import React, { useState, useRef } from "react";
...

const Page = () => {
  const formikRef = useRef();

  const setValues = () => {
    console.log("hh");
    setInitialValues({ ...initialValues, age: 75 });
    formikRef.current.resetForm();
  };
  ...
  return (
    <div>
      <button onClick={setValues}>API Call</button>

      <Formik
        ref={(ref) => {
          formikRef.current = ref;
        }}
        initialValues={initialValues}
        onSubmit={submit}
        validationSchema={validationSchema}
        enableReinitialize
      >
        ...
      </Formik>
    </div>
  );
};

EDIT I added one more part that covers modifying initial values. First you need to set initialValues and than do formikRef.current.resetForm().

NOTE

If you upgrade Formik to 2.x.x ref is changed to innerRef:

<Formik
  innerRef={(ref) => {
    formikRef.current = ref;
  }}
></Formik>;