mirror of
https://github.com/lukevella/rallly.git
synced 2025-04-29 18:26:34 +02:00
Use local storage for guest user preferences
This commit is contained in:
parent
6c877fe8ad
commit
b8b51e5837
1 changed files with 41 additions and 7 deletions
|
@ -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<Preferences>) => Promise<void>;
|
||||
|
@ -31,15 +34,46 @@ export const PreferencesProvider = ({
|
|||
initialValue: Partial<Preferences>;
|
||||
}) => {
|
||||
const { user } = useUser();
|
||||
const [preferences, setPreferences] = useSetState<Preferences>(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 (
|
||||
<PreferencesContext.Provider
|
||||
value={{
|
||||
preferences,
|
||||
preferences: {
|
||||
timeZone: preferredTimezone,
|
||||
timeFormat: preferredTimeFormat,
|
||||
weekStart: preferredWeekStart,
|
||||
},
|
||||
updatePreferences: async (newPreferences) => {
|
||||
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,
|
||||
|
|
Loading…
Add table
Reference in a new issue