formik
formik copied to clipboard
onPaste + setFieldValue does not work as intended
Bug report
Current Behavior
When trying to setFieldValue within onPaste callback prepends the field value instead of replacing it.
Expected behavior
setFieldValue should replace the field value
Reproducible example
The templates are outdated (very old React/Formik versions) I couldn't get them to work without refactoring the entire thing. This is the code I'm using
onPaste={async (event: ClipboardEvent<HTMLInputElement>) => {
const reg = /:(?<port>[0-9]+)/
const valueArray = event.clipboardData.getData('text/plain').split(reg);
if (Number(valueArray[1])) {
setFieldValue('url', valueArray[0]);
setFieldValue('port', valueArray[1]);
}
}
Your environment
Software | Version(s) |
---|---|
Formik | 2.2.9 |
React | 17.0.2 |
TypeScript | 4.4.2 |
Browser | Chrome latest |
npm/Yarn | Yarn |
Operating System | Ubuntu 20 |
event.preventDefault() seems to sort it, not sure if this is just my miss here
Seems like it is not formik error itself. Yes event.preventDefault()
should fix your problem.
There is an example without formik and it works as you described:
import { useState } from 'react';
export const RegularForm = () => {
const [firstName, setFirstName] = useState<string>("");
const [lastName, setLastName] = useState<string>("");
return (
<form>
<input
type="text"
name="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
onPaste={(event) => {
const valueArray = event.clipboardData.getData('text/plain').split(" ");
setFirstName(valueArray[0]);
setLastName(valueArray[1]);
}}
/>
<input
type="text"
name="lastName"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>
</form>
);
};