formik icon indicating copy to clipboard operation
formik copied to clipboard

onPaste + setFieldValue does not work as intended

Open gnesher opened this issue 1 year ago • 2 comments

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

gnesher avatar Dec 26 '23 10:12 gnesher

event.preventDefault() seems to sort it, not sure if this is just my miss here

gnesher avatar Dec 26 '23 11:12 gnesher

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>
    );
};

ChronicusUA avatar Apr 26 '24 10:04 ChronicusUA