Form/Common: disable save button if form values are not changed

This commit is contained in:
vchikalkin 2024-02-01 18:17:23 +03:00
parent 381ba678d9
commit be938b4d62
2 changed files with 8 additions and 2 deletions

View File

@ -9,7 +9,7 @@ import { useCallback } from 'react';
import { useContext } from 'react';
export function Buttons() {
const { reset, resetValidation, setValidation, values } = useFormStore();
const { reset, resetValidation, setValidation, status, values } = useFormStore();
const { pageUrlParams, setFormState } = useContext(FormContext);
const router = useRouter();
@ -69,7 +69,9 @@ export function Buttons() {
<Button intent="outline-secondary" onClick={handleRetract}>
Возврат на доработку
</Button>
<Button onClick={handleSave}>Сохранить</Button>
<Button onClick={handleSave} disabled={status !== 'edited'}>
Сохранить
</Button>
</div>
);
}

View File

@ -15,6 +15,7 @@ type FormState = {
resetValidation: () => void;
setValidation: (input: { name: string } & ElementValidation) => void;
setValue: ({ name, value }: { name: string; value: Values[number] }) => void;
status?: 'init' | 'edited';
validation: Record<string, ElementValidation | undefined>;
values: Values;
};
@ -24,10 +25,12 @@ export const useFormStore = create<FormState>((set) => ({
init: (values) =>
set(() => ({
defaultValues: values,
status: 'init',
values,
})),
reset: () =>
set((state) => ({
status: 'init',
validation: {},
values: state.defaultValues,
})),
@ -44,6 +47,7 @@ export const useFormStore = create<FormState>((set) => ({
})),
setValue: ({ name, value }) =>
set((state) => ({
status: 'edited',
validation: {
...state.validation,
[name]: undefined,