Skip to content

Commit 1ce9814

Browse files
committed
Fix: 「クリア」が正常に動作するように
1 parent f052ec7 commit 1ce9814

4 files changed

Lines changed: 189 additions & 14 deletions

File tree

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
"react-dom": "^18.3.1",
3636
"react-hook-form": "^7.53.0",
3737
"react-json-view": "^1.21.3",
38+
"react-use": "^17.5.1",
3839
"rsuite": "^5.70.0",
3940
"timezones-list": "^3.0.3",
4041
"uuid": "^10.0.0"

src/components/common/Form/ClearButton.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ type Props = {
1010
};
1111

1212
export const ClearButton: FC<Props> = ({ name, title = 'クリア', onClick = null }) => {
13-
const { resetField, watch, setValue } = useFormContext();
13+
const { resetField } = useFormContext();
1414

1515
const onClickInputClear = useCallback(() => {
1616
resetField(name);

src/hooks/useFormPersistence.ts

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { useEffect } from 'react';
1+
import { useEffect, useState } from 'react';
22
import type { UseFormReturn } from 'react-hook-form';
3+
import { useEffectOnce } from 'react-use';
34

45
// フォームの情報をlocalStorageに保存して永続化する
56
export const useFormPersistence = <T>(
@@ -13,17 +14,26 @@ export const useFormPersistence = <T>(
1314
formState: { isDirty },
1415
} = methods;
1516
const formData = watch();
17+
const [isDefault, setIsDefault] = useState(true);
1618

1719
useEffect(() => {
18-
const defaultValues = JSON.parse(localStorage.getItem(name));
19-
if (!isDirty) {
20-
setCallback(defaultValues);
20+
try {
21+
const defaultValues = JSON.parse(localStorage.getItem(name));
22+
if (!isDirty && isDefault) {
23+
setCallback(defaultValues);
24+
// console.log('get', { name, defaultValues });
25+
setIsDefault(false);
26+
}
27+
} catch (e) {
28+
console.error(e);
2129
}
22-
}, [isDirty]);
30+
}, [isDirty, isDefault]);
2331

2432
useEffect(() => {
25-
if (isDirty) {
33+
// console.log('set1', { name, isDirty, isDefault, formData });
34+
if (isDirty || (!isDirty && !isDefault)) {
2635
localStorage.setItem(name, JSON.stringify(formData));
36+
// console.log('set2', { name, isDirty, isDefault, formData });
2737
}
28-
}, [formData, isDirty]);
38+
}, [formData, isDirty, isDefault]);
2939
};

0 commit comments

Comments
 (0)