el.xwx.moe/store/account.ts

44 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-05-18 13:02:17 -05:00
import { create } from "zustand";
2023-05-20 14:25:00 -05:00
import { AccountSettings } from "@/types/global";
2023-05-18 13:02:17 -05:00
type ResponseObject = {
ok: boolean;
2023-07-19 15:39:59 -05:00
data: Omit<AccountSettings, "password"> | object | string;
};
2023-05-18 13:02:17 -05:00
type AccountStore = {
account: AccountSettings;
setAccount: (id: number) => void;
updateAccount: (user: AccountSettings) => Promise<ResponseObject>;
2023-05-18 13:02:17 -05:00
};
const useAccountStore = create<AccountStore>()((set) => ({
account: {} as AccountSettings,
setAccount: async (id) => {
const response = await fetch(`/api/routes/users?id=${id}`);
2023-05-18 13:02:17 -05:00
const data = await response.json();
2023-06-08 08:39:22 -05:00
const profilePic = `/api/avatar/${data.response.id}?${Date.now()}`;
2023-05-18 13:02:17 -05:00
if (response.ok) set({ account: { ...data.response, profilePic } });
2023-05-20 14:25:00 -05:00
},
updateAccount: async (user) => {
const response = await fetch("/api/routes/users", {
method: "PUT",
body: JSON.stringify(user),
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
2023-06-08 08:39:22 -05:00
if (response.ok) set({ account: { ...data.response } });
2023-05-21 04:54:42 -05:00
return { ok: response.ok, data: data.response };
2023-05-18 13:02:17 -05:00
},
}));
export default useAccountStore;