Skip to content

Commit c1265e1

Browse files
committed
feat: change zod schema for form validation in local persistence
1 parent b003703 commit c1265e1

File tree

2 files changed

+28
-11
lines changed

2 files changed

+28
-11
lines changed
Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,34 @@
1+
import { atom } from 'jotai';
12
import { atomWithStorage } from 'jotai/utils';
2-
import type { LocalGameFormSchema } from '@/game/local/setup/_components/form';
3+
import type { DeepPartial } from 'react-hook-form';
4+
import type { LocalGameFormSchema } from '../local/setup/_components/form';
35

4-
export const gameSettingsAtom = atomWithStorage<LocalGameFormSchema>(
6+
const baseGameSettingsAtom = atomWithStorage<LocalGameFormSchema>(
57
'gameSettings',
68
{
79
players: [],
810
numberOfSpies: '1',
911
randomNumberOfSpies: false,
1012
},
1113
);
14+
15+
export const gameSettingsAtom = atom(
16+
(get) => get(baseGameSettingsAtom),
17+
(
18+
get,
19+
set,
20+
update:
21+
| DeepPartial<LocalGameFormSchema>
22+
| ((prev: LocalGameFormSchema) => LocalGameFormSchema),
23+
) => {
24+
const newValue =
25+
typeof update === 'function' ? update(get(baseGameSettingsAtom)) : update;
26+
set(baseGameSettingsAtom, {
27+
players: (newValue.players ?? []).map((player) => ({
28+
name: player?.name ?? '',
29+
})),
30+
numberOfSpies: newValue.numberOfSpies ?? '1',
31+
randomNumberOfSpies: newValue.randomNumberOfSpies ?? false,
32+
});
33+
},
34+
);

app/[lang]/game/local/setup/_components/form.tsx

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -76,18 +76,12 @@ export const LocalUsersForm: FC<{ dict: Dictionary; lang: string }> = ({
7676

7777
useEffect(() => {
7878
const { unsubscribe } = form.watch((value) => {
79-
const result = localGameFormSchema.safeParse(value);
80-
if (form.formState.isDirty && result.success) {
81-
setGameSettings(result.data);
79+
if (form.formState.isDirty) {
80+
setGameSettings(value);
8281
}
8382
});
8483
return () => unsubscribe();
85-
}, [
86-
form.watch,
87-
form.formState.isDirty,
88-
localGameFormSchema,
89-
setGameSettings,
90-
]);
84+
}, [form.watch, form.formState.isDirty, setGameSettings]);
9185

9286
useEffect(() => {
9387
if (hasHydrated.current) {

0 commit comments

Comments
 (0)