scoresaber-reloaded-v2/src/store/settingsStore.ts

50 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-10-19 19:31:05 +00:00
"use client";
2023-10-21 21:16:46 +00:00
import { getPlayerInfo } from "@/utils/scoresaber/api";
2023-10-19 19:31:05 +00:00
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
2023-10-19 19:31:05 +00:00
2023-10-21 21:16:46 +00:00
interface SettingsStore {
userId: string | undefined;
profilePicture: string | undefined;
setUserId: (userId: string) => void;
setProfilePicture: (profilePicture: string) => void;
refreshProfile: () => void;
2023-10-21 21:16:46 +00:00
}
export const useSettingsStore = create<SettingsStore>()(
2023-10-19 19:31:05 +00:00
persist(
2023-10-21 21:16:46 +00:00
(set) => ({
userId: undefined,
profilePicture: undefined,
2023-10-19 19:31:05 +00:00
2023-10-21 21:16:46 +00:00
setUserId: (userId: string) => {
set({ userId });
},
2023-10-22 01:17:21 +00:00
2023-10-21 21:16:46 +00:00
setProfilePicture: (profilePicture: string) => set({ profilePicture }),
2023-10-22 01:17:21 +00:00
async refreshProfile() {
const id = useSettingsStore.getState().userId;
if (!id) return;
const profile = await getPlayerInfo(id);
if (profile == undefined || profile == null) return;
useSettingsStore.setState({
userId: profile.id,
profilePicture: profile.profilePicture,
});
console.log("Updated profile:", profile.id);
},
2023-10-19 19:31:05 +00:00
}),
{
2023-10-21 21:16:46 +00:00
name: "settings",
storage: createJSONStorage(() => localStorage),
2023-10-19 19:31:05 +00:00
},
),
);
2023-10-21 21:16:46 +00:00
useSettingsStore.getState().refreshProfile();