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

57 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-10-19 19:31:05 +00:00
"use client";
import { SortType, SortTypes } from "@/types/SortTypes";
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;
lastUsedSortType: SortType;
2023-10-21 21:16:46 +00:00
setUserId: (userId: string) => void;
setProfilePicture: (profilePicture: string) => void;
setLastUsedSortType: (sortType: SortType) => 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,
lastUsedSortType: SortTypes.top,
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
setLastUsedSortType: (sortType: SortType) =>
set({ lastUsedSortType: sortType }),
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();