From b8b51e583704ef9df5684feb8b789bd6db95e6b7 Mon Sep 17 00:00:00 2001 From: Luke Vella Date: Wed, 23 Apr 2025 16:17:18 +0100 Subject: [PATCH] Use local storage for guest user preferences --- apps/web/src/contexts/preferences.tsx | 48 +++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 7 deletions(-) diff --git a/apps/web/src/contexts/preferences.tsx b/apps/web/src/contexts/preferences.tsx index 1a6c28f5b..9d9236743 100644 --- a/apps/web/src/contexts/preferences.tsx +++ b/apps/web/src/contexts/preferences.tsx @@ -2,18 +2,21 @@ import type { TimeFormat } from "@rallly/database"; import React from "react"; -import { useSetState } from "react-use"; +import { useLocalStorage } from "react-use"; +import { z } from "zod"; import { useRequiredContext } from "@/components/use-required-context"; import { useUser } from "@/components/user-provider"; import { trpc } from "@/trpc/client"; type Preferences = { - timeZone?: string | null; - timeFormat?: TimeFormat | null; - weekStart?: number | null; + timeZone?: string; + timeFormat?: TimeFormat; + weekStart?: number; }; +const timeFormatSchema = z.enum(["hours12", "hours24"]); + type PreferencesContextValue = { preferences: Preferences; updatePreferences: (preferences: Partial) => Promise; @@ -31,15 +34,46 @@ export const PreferencesProvider = ({ initialValue: Partial; }) => { const { user } = useUser(); - const [preferences, setPreferences] = useSetState(initialValue); + const [preferredTimezone, setPreferredTimezone] = useLocalStorage( + "rallly.preferredTimezone", + initialValue.timeZone, + ); + const [preferredTimeFormat, setPreferredTimeFormat] = useLocalStorage( + "rallly.preferredTimeFormat", + initialValue.timeFormat, + { + raw: false, + serializer: timeFormatSchema.parse, + deserializer: timeFormatSchema.optional().catch(undefined).parse, + }, + ); + const [preferredWeekStart, setPreferredWeekStart] = useLocalStorage( + "rallly.preferredWeekStart", + initialValue.weekStart, + ); const updatePreferences = trpc.user.updatePreferences.useMutation(); return ( { - setPreferences(newPreferences); + if (newPreferences.timeZone) { + setPreferredTimezone(newPreferences.timeZone); + } + + if (newPreferences.timeFormat) { + setPreferredTimeFormat(newPreferences.timeFormat); + } + + if (newPreferences.weekStart) { + setPreferredWeekStart(newPreferences.weekStart); + } + if (!user.isGuest) { await updatePreferences.mutateAsync({ timeZone: newPreferences.timeZone ?? undefined,