formik icon indicating copy to clipboard operation
formik copied to clipboard

is There a way to trigger onChange event when Chome autofill feature is used?

Open andriy-fuzz opened this issue 7 years ago • 30 comments

❓Question

I came across an issue, where users are using Chrome Autofill to enter saved inputs into the form. The result is that Chrome autofill feature does not trigger onChange events in form. And that results in form being invalid and form values technically empty even though visually they have values. See image below.

This issue is also expressed in react and other libraries. Link: https://github.com/facebook/react/issues/1159

I am curious if anyone came across solutions that are easy to implement?

screen shot 2018-10-25 at 5 03 41 pm

andriy-fuzz avatar Oct 25 '18 21:10 andriy-fuzz

@crosscompile didn't we fix this somehow on our login form?

jaredpalmer avatar Oct 30 '18 16:10 jaredpalmer

@jaredpalmer I am trying to programmatically trigger the form to validate. Without going into details, I have a hacky solution, but what would make it easier is if I get programmatically trigger formik to validate the field/forms. I am triggering the fields to focus/blur as can be shown in link below, but formik is not validating for some reason even though validateOnBlur is set to true.

  • https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur

andriy-fuzz avatar Nov 01 '18 15:11 andriy-fuzz

Hola! So here's the deal, between open source and my day job and life and what not, I have a lot to manage, so I use a GitHub bot to automate a few things here and there. This particular GitHub bot is going to mark this as stale because it has not had recent activity for a while. It will be closed if no further activity occurs in a few days. Do not take this personally--seriously--this is a completely automated action. If this is a mistake, just make a comment, DM me, send a carrier pidgeon, or a smoke signal.

stale[bot] avatar Dec 31 '18 15:12 stale[bot]

ProBot automatically closed this due to inactivity. Holler if this is a mistake, and we'll re-open it.

stale[bot] avatar Jan 07 '19 18:01 stale[bot]

I have the same problem @andriy-fuzz how you solved it?

addamove avatar Jan 31 '19 14:01 addamove

This is still an issue, at least for fields that are validated onBlur. Users have to click on the form field in order to validate it, even if Chrome autofilled them.

gsoverini avatar Apr 12 '19 18:04 gsoverini

I also have this problem is there a solution?

svey avatar Jul 19 '19 02:07 svey

Same here. The same problem.

jojo-tutor avatar Aug 01 '19 14:08 jojo-tutor

Any updates on this issue? I am having problems with Google Places Autocomplete and Formik

FatehAK avatar Oct 31 '19 12:10 FatehAK

This issue still exists at the end of 2019. Has anyone successfully implemented a solution/workaround for this?

TerrorOnMtHyjal avatar Dec 17 '19 10:12 TerrorOnMtHyjal

same problem here. not so much validation, but for style application when the field is filled. On first render field.value is an empty string (as passed in from initialValues), onChange is not triggered until user interaction, so the field is filled but there is no chance to update the style

agos avatar Feb 05 '20 11:02 agos

Also seeing this issue. An additional oddity is that the validation seems to kick in when clicking anywhere on the page, even outside of the form. 👻

colepeters avatar Jun 24 '20 19:06 colepeters

Same problem and we don`t see appropriate workaround. Please reopen and fix.

ioliinyk avatar Oct 05 '20 10:10 ioliinyk

We have the same problem. Please, reopen and fix

Egenie-mih avatar Nov 16 '20 12:11 Egenie-mih

I has the same problem. Still no solution?

pcyglesias avatar Feb 09 '21 17:02 pcyglesias

We have the same issue...

torocsik-marton avatar Feb 15 '21 13:02 torocsik-marton

The same problem..

o1st avatar Mar 01 '21 18:03 o1st

Same problem, there is any fix for that? Thanks guys!

lironezra avatar Jun 27 '21 09:06 lironezra

Having the same problem.

mattrockwell avatar Jul 07 '21 11:07 mattrockwell

Assuming everyone is having the problem on page load and not afterwards, (autofill is populated on page load, instead of clicking the "Fill" button), page-load autofill generally occurs before React has had a chance to initialize and trigger the synthetic events that Formik uses to update its state.

A way to solve this in the Field component would be to create a ref to its underlying input / select / textarea / etc, and then on mount check if the value has changed from the initial value, and is not empty.

If this issue occurs when performing "Fill" commands manually, that's another issue entirely, and would likely be a problem with Autofill vendors setting input.value = "value" without dispatching the actual change event, and I don't know how we'd work around that.

Pseudo-solution, with a few problems.


const Field = (props) => {
  const maybeRef = React.useRef<HTMLElement>(null);

  // we let users pass a ref themselves... I'm sure this typescript won't work
  const ref = props.innerRef || maybeRef;

  // this should already be done somewhere or at least is in my v3 PR.
  const [field, meta, helpers] = useField(propsUsedForUseField);

  const maybeSyncAutofill = useEventCallback(() => {
        // this doesn't work for checkboxes, radios, multi-select, etc
        const input: HTMLElement = ref.current;

        if (
            input instanceof HTMLInputElement &&
            input.type !== "radio" &&
            input.type !== "checkbox" && 
            input.value &&
            input.value !== field.value
        ) {
            helpers.setValue(input.value);
        }
  });

  const useEffect(() => {
    maybeSyncAutofill();
  }, []);

  // there are a bunch of different types of initialization, here's one example
  const {
    validate,
    ...otherNonInputProps,
    ...inputProps,
  }

  return React.createElement(props.as, {...inputProps, ref});
}

johnrom avatar Jul 07 '21 15:07 johnrom

+1. running into this issue

handhikadj avatar Oct 08 '21 09:10 handhikadj

+1

terrynguyen255 avatar Oct 25 '21 10:10 terrynguyen255

I hope this bug can be resolved on formik but I took inspiration from @johnrom suggestion to fix the bug on my input field as shown below

const Field = (props) => {
  const inputRef = React.useRef<HTMLElement>(null);

  // this should already be done somewhere or at least is in my v3 PR.
  const [{ value }, meta,{ setValue }] = useField(propsUsedForUseField);

  useEffect(() => {
    const input: HTMLElement = inputRef.current
    if (
      input instanceof HTMLInputElement &&
        input.value &&
        input.value !== value
    ) {
      setValue(input.value)
    }
  }, [setValue])

  return ( <Input ref={inputRef} />)
}

Hope this helps unblock somebody

Damilare1 avatar Nov 08 '21 14:11 Damilare1

It's 2023. This is still a problem (not just for Chrome though). Safari and Firefox too. Google Places Autocomplete doesn't get triggered if field is auto-filled by browser. I worked around it by manually dispatching a change event to take user back to that field.

billylo1 avatar May 22 '23 13:05 billylo1

+1 @billylo1 would you be able to provide an abbreviated example of how you went about "manually dispatching a change event to take user back to that field."? I've tried triggering .focus(), input & change events (via dispatchEvent) on the form inputs, but haven't had any success.

ljones87 avatar Jun 01 '23 21:06 ljones87

try: https://www.npmjs.com/package/detect-autofill

add eventListener to Field component and set flag "isAutocompleted" to form state

Anastasia-kot avatar Nov 30 '23 16:11 Anastasia-kot

I couldn't get any of the above options working correctly locally, so I put together a very hackey solution. The below code is implemented within our "AddressComponent", which is a component housing of all the Formik Field address inputs and the google address api widget from react-google-autocomplete

  const [addressAutoFilled, setAddressAutoFilled] = useState(false)
  const [autoFillValidated, setAutoFillValidated] = useState(false)

  if (addressAutoFilled && !autoFillValidated) {
    validateForm()
    setTimeout(() => setAutoFillValidated(true), 1)
  }

Just before calling our function, handleAddressSelect, I set both of the autocomplete tracking variables to false so the process will re-validate if they choose a new address

 onPlaceSelected: (addressDetails) => {
      setAutoFillValidated(false)
      setAddressAutoFilled(false)
      handleAddressSelect(addressDetails)
    },

handleAddressSelect then sets all our Formik address fields and finishes with setAddressAutoFilled(true).

I tried briefly using formik state and setFieldValue for the state values above, but did not have the same effect.

ljones87 avatar Jan 10 '24 20:01 ljones87

Any updates on this issue? I am having problems with Google Places Autocomplete and Formik

Same here

Vik2ry avatar Jul 19 '24 20:07 Vik2ry