jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.71k stars 2.77k forks source link

Call formik.setFieldValue() with previous value as parameter #3960

Open wilhei opened 3 months ago

wilhei commented 3 months ago

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(false);
setTestvalue((prev) => prev + num);

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