Skip to content

Commit

Permalink
fix cached forms not being removed when submitted
Browse files Browse the repository at this point in the history
  • Loading branch information
hzrd149 committed Aug 31, 2024
1 parent edd7418 commit 8deeec4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/hooks/use-cache-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ export default function useCacheForm<TFieldValues extends FieldValues = FieldVal
const log = useMemo(() => (key ? logger.extend(`CachedForm:${key}`) : () => {}), [key]);
const storageKey = key && "cached-form-" + key;

const stateRef = useRef<UseFormStateReturn<TFieldValues>>(state);
stateRef.current = state;
const isSubmitted = useRef<boolean>(state.isSubmitted);
isSubmitted.current = state.isSubmitted;

// NOTE: this watches the state
state.isDirty;
state.isSubmitted;
const isSubmitting = useRef<boolean>(state.isSubmitting);
isSubmitting.current = state.isSubmitting;

const isDirty = useRef<boolean>(state.isDirty);
isDirty.current = state.isDirty;

useEffect(() => {
if (!storageKey) return;
Expand All @@ -44,10 +46,10 @@ export default function useCacheForm<TFieldValues extends FieldValues = FieldVal

// save previous key on change or unmount
return () => {
if (stateRef.current.isSubmitted) {
if (isSubmitted.current || isSubmitting.current) {
log("Removing because submitted");
localStorage.removeItem(storageKey);
} else if (stateRef.current.isDirty) {
} else if (isDirty.current) {
const values = getValues();
log("Saving form", values);
localStorage.setItem(storageKey, JSON.stringify(values));
Expand All @@ -58,10 +60,10 @@ export default function useCacheForm<TFieldValues extends FieldValues = FieldVal
const saveOnClose = useCallback(() => {
if (!storageKey) return;

if (stateRef.current.isSubmitted) {
if (isSubmitted.current || isSubmitting.current) {
log("Removing because submitted");
localStorage.removeItem(storageKey);
} else if (stateRef.current.isDirty) {
} else if (isDirty.current) {
const values = getValues();
log("Saving form", values);
localStorage.setItem(storageKey, JSON.stringify(values));
Expand Down
1 change: 1 addition & 0 deletions src/views/thread/components/reply-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export default function ReplyForm({ item, onCancel, onSubmitted, replyKind = kin
},
mode: "all",
});

const clearCache = useCacheForm<{ content: string }>(`reply-${item.event.id}`, getValues, reset, formState);

const contentMentions = getPubkeysMentionedInContent(getValues().content);
Expand Down

0 comments on commit 8deeec4

Please sign in to comment.