Skip to content

Commit

Permalink
[@mantine/form] Fix onValuesChange using stale values (#6392)
Browse files Browse the repository at this point in the history
  • Loading branch information
rtivital committed Jun 28, 2024
1 parent 831041b commit cfd8b4e
Showing 1 changed file with 32 additions and 26 deletions.
58 changes: 32 additions & 26 deletions packages/@mantine/form/src/hooks/use-form-values/use-form-values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,44 +75,50 @@ export function useFormValues<Values extends Record<PropertyKey, any>>({
[onValuesChange]
);

const setFieldValue = useCallback((payload: SetFieldValueInput<Values>) => {
const currentValue = getPath(payload.path, refValues.current);
const updatedValue =
payload.value instanceof Function ? payload.value(currentValue) : payload.value;

if (currentValue !== updatedValue) {
const previousValues = refValues.current;
const updatedValues = setPath(payload.path, updatedValue, refValues.current);
setValues({ values: updatedValues, updateState: payload.updateState });

payload.subscribers
?.filter(Boolean)
.forEach((subscriber) =>
subscriber!({ path: payload.path, updatedValues, previousValues })
);
}
}, []);
const setFieldValue = useCallback(
(payload: SetFieldValueInput<Values>) => {
const currentValue = getPath(payload.path, refValues.current);
const updatedValue =
payload.value instanceof Function ? payload.value(currentValue) : payload.value;

if (currentValue !== updatedValue) {
const previousValues = refValues.current;
const updatedValues = setPath(payload.path, updatedValue, refValues.current);
setValues({ values: updatedValues, updateState: payload.updateState });

payload.subscribers
?.filter(Boolean)
.forEach((subscriber) =>
subscriber!({ path: payload.path, updatedValues, previousValues })
);
}
},
[setValues]
);

const setValuesSnapshot = useCallback((payload: Values) => {
valuesSnapshot.current = payload;
}, []);

const initialize = useCallback((values: Values, onInitialize: () => void) => {
if (!initialized.current) {
initialized.current = true;
setValues({ values, updateState: mode === 'controlled' });
setValuesSnapshot(values);
onInitialize();
}
}, []);
const initialize = useCallback(
(values: Values, onInitialize: () => void) => {
if (!initialized.current) {
initialized.current = true;
setValues({ values, updateState: mode === 'controlled' });
setValuesSnapshot(values);
onInitialize();
}
},
[setValues]
);

const resetValues = useCallback(() => {
setValues({
values: valuesSnapshot.current,
updateState: true,
mergeWithPreviousValues: false,
});
}, []);
}, [setValues]);

const getValues = useCallback(() => refValues.current, []);

Expand Down

0 comments on commit cfd8b4e

Please sign in to comment.