Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

onPaste + setFieldValue does not work as intended #3932

Open
gnesher opened this issue Dec 26, 2023 · 2 comments
Open

onPaste + setFieldValue does not work as intended #3932

gnesher opened this issue Dec 26, 2023 · 2 comments

Comments

@gnesher
Copy link

gnesher commented Dec 26, 2023

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
Copy link
Author

gnesher commented Dec 26, 2023

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

@ChronicusUA
Copy link
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants