formik icon indicating copy to clipboard operation
formik copied to clipboard

Call formik.setFieldValue() with previous value as parameter

Open wilhei opened this issue 1 year ago • 5 comments

Feature request

Current Behavior

It is not possible to call formik.setFieldValue('name', value) multiple times async. without overwriting the other values. Let's take a look at following simple example:

const onButtonClick = () =>{
  Array.from(Array(5).keys())
   .forEach((num) => formik.setFieldValue("testvalue", formik.values.testvalue + num));
  };
}

The problem is, that we end up with a result, where only one num was added, instead of a sum of all. All previous added nums were overwritten.

Desired Behavior

Beeing able to pass a function containing the previous value as parameter (like we can do in react useState setter method).

In React we can do following:

const [testValue, setTestvalue] = React.useState(0);
setTestvalue((prev) => prev + 10);

It would be great to have the same in formik:

const onButtonClick = () =>{
  Array.from(Array(5).keys())
   .forEach((num) => formik.setFieldValue("testvalue", (prev) => prev + num));
  };
}

So in this example we do not use the "start value" everywhere, but we always use the already updated value of previous called functions.

Suggested Solution

see Desired Behavior

Who does this impact? Who is this for?

All react developer, which need to run multiple async funtions. In my example I upload multiple images and update the uploading states async.

Describe alternatives you've considered

Use a React.useState variable and use the setter method with previous value. But I need to sync it all the time with the formik values to be able to use the formik.dirty variable.

Additional context

wilhei avatar Mar 07 '24 15:03 wilhei

This would be really helpful, any update on this?

ubaidkolad avatar Oct 22 '24 08:10 ubaidkolad

any update?

sovetski avatar Feb 25 '25 10:02 sovetski

any update?

singh-ekjot avatar May 28 '25 07:05 singh-ekjot

any update?

gdeggau avatar Aug 27 '25 00:08 gdeggau

It's been merged and is available in 2.4.9 (and possibly earlier)

@ChronicusUA Many thanks for the PR! This is definitely making things easier!

stupidSheep avatar Nov 14 '25 07:11 stupidSheep