useUserInfoStore.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { userInfoApi } from "@/api/login";
  2. import { create } from "zustand";
  3. import { createJSONStorage, devtools, persist } from "zustand/middleware";
  4. interface State {
  5. userInfo: any;
  6. }
  7. interface Action {
  8. setUserInfo: (lang: State["userInfo"]) => void;
  9. reset: () => void;
  10. getUserInfo: () => void;
  11. }
  12. const initialState: State = {
  13. userInfo: "",
  14. };
  15. export const useUserInfoStore = create<State & Action>()(
  16. devtools(
  17. persist(
  18. (set) => {
  19. return {
  20. ...initialState,
  21. setUserInfo: (userInfo: State["userInfo"]) =>
  22. set({
  23. userInfo,
  24. }),
  25. reset: () => {
  26. set(initialState);
  27. },
  28. async getUserInfo() {
  29. const res = await userInfoApi();
  30. if (res?.data) {
  31. set({ userInfo: res?.data });
  32. }
  33. },
  34. };
  35. },
  36. {
  37. name: "globalStore",
  38. storage: createJSONStorage(() => localStorage),
  39. }
  40. ),
  41. { name: "globalStore" }
  42. )
  43. );