Skip to content

Commit

Permalink
fix: don't overwrite user input when field recently changed
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisvxd committed Oct 7, 2024
1 parent 8c706cd commit 6126040
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion packages/core/components/AutoField/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
Expand Down Expand Up @@ -185,6 +186,9 @@ function AutoFieldInternal<
return <Render {...mergedProps}>{children}</Render>;
}

// Don't let external value changes update this if it's changed manually in the last X ms
const RECENT_CHANGE_TIMEOUT = 200;

export function AutoFieldPrivate<
ValueType = any,
FieldType extends Field<ValueType> = Field<ValueType>
Expand All @@ -197,6 +201,9 @@ export function AutoFieldPrivate<

const [localValue, setLocalValue] = useState(value);

const [recentlyChanged, setRecentlyChanged] = useState(false);
const timeoutRef = useRef<NodeJS.Timeout>();

const onChangeDb = useDebouncedCallback(
(val, ui) => {
onChange(val, ui);
Expand All @@ -207,11 +214,22 @@ export function AutoFieldPrivate<

const onChangeLocal = useCallback((val: any, ui?: Partial<UiState>) => {
setLocalValue(val);

setRecentlyChanged(true);

clearTimeout(timeoutRef.current);

timeoutRef.current = setTimeout(() => {
setRecentlyChanged(false);
}, RECENT_CHANGE_TIMEOUT);

onChangeDb(val, ui);
}, []);

useEffect(() => {
setLocalValue(value);
if (!recentlyChanged) {
setLocalValue(value);
}
}, [value]);

const localProps = {
Expand Down

0 comments on commit 6126040

Please sign in to comment.