Call formik.setFieldValue() with previous value as parameter
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
This would be really helpful, any update on this?
any update?
any update?
any update?
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!