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

fix: Check for event.preventDefault() before setting state #18

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,6 @@ function invariant(value: any, message?: string) {
const getInputId = (name: string, reactId: string) => `${name}--${reactId}`;
const getErrorsId = (name: string, reactId: string) =>
`${name}-errors--${reactId}`;
const callAll =
(...fns: (Function | undefined)[]) =>
(...args: any[]) =>
fns.forEach((fn) => fn?.(...args));
const composeClassNames = (classes: Array<string | undefined>) =>
classes.filter((v) => v).join(" ");
const omit = (
Expand Down Expand Up @@ -510,10 +506,13 @@ export function useValidatedInput<T extends FormValidations>(
id: getInputId(name, id),
className: getClasses("input", attrs.className),
defaultValue: serverFormInfo?.submittedFormData?.lastName,
onChange: callAll(onChange, (e: React.ChangeEvent<HTMLInputElement>) => {
setDirty(true);
setValue(e.target.value);
}),
onChange: (event: React.ChangeEvent<HTMLInputElement>) => {
onChange?.(event);
if (!event.defaultPrevented) {
setDirty(true);
setValue(event.target.value);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure this is what we want if the change event is prevented - since that happens after the input value has been set in the DOM (at least for text and similar inputs - would need to look closer on radio/checkbox). If we don't set the controlled value we can get into weird UI states:

Screen Shot 2022-09-29 at 8 43 07 AM

Users can use onKeyDown currently to prevent typed characters.

I've been thinking for a while too that I'd like to take a stab at making this entire library uncontrolled and just always use inputEl.value, which would remove this setValue entirely. I think that's feasible and would get rid of the useState so might have the worlds tiniest perf improvement 🎻

}
},
...(showErrors
? {
"aria-invalid": true,
Expand Down