useProfile.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. "use client";
  2. import { useCallback, useEffect, useState } from "react";
  3. import {
  4. fetchProfile,
  5. updateProfile,
  6. uploadAvatar,
  7. UpdateProfilePayload,
  8. } from "../../agent/services/profileApi";
  9. import { Profile } from "../../agent/types";
  10. interface UseProfileOptions {
  11. userId: number | null;
  12. enabled?: boolean;
  13. }
  14. export function useProfile({ userId, enabled = true }: UseProfileOptions) {
  15. const [profile, setProfile] = useState<Profile | null>(null);
  16. const [loading, setLoading] = useState(false);
  17. const [updating, setUpdating] = useState(false);
  18. const [uploading, setUploading] = useState(false);
  19. // 加载个人资料
  20. const loadProfile = useCallback(async () => {
  21. if (!userId || !enabled) {
  22. return;
  23. }
  24. setLoading(true);
  25. try {
  26. const data = await fetchProfile(userId);
  27. setProfile(data);
  28. } catch (error) {
  29. console.error("获取个人资料失败:", error);
  30. } finally {
  31. setLoading(false);
  32. }
  33. }, [userId, enabled]);
  34. // 初始化时加载个人资料
  35. useEffect(() => {
  36. loadProfile();
  37. }, [loadProfile]);
  38. // 更新个人资料
  39. const update = useCallback(
  40. async (payload: UpdateProfilePayload) => {
  41. if (!userId) {
  42. throw new Error("用户ID不能为空");
  43. }
  44. setUpdating(true);
  45. try {
  46. const updated = await updateProfile(userId, payload);
  47. setProfile(updated);
  48. return updated;
  49. } finally {
  50. setUpdating(false);
  51. }
  52. },
  53. [userId]
  54. );
  55. // 上传头像
  56. const upload = useCallback(
  57. async (file: File) => {
  58. if (!userId) {
  59. throw new Error("用户ID不能为空");
  60. }
  61. setUploading(true);
  62. try {
  63. const updated = await uploadAvatar(userId, file);
  64. setProfile(updated);
  65. return updated;
  66. } finally {
  67. setUploading(false);
  68. }
  69. },
  70. [userId]
  71. );
  72. // 刷新个人资料
  73. const refresh = useCallback(() => {
  74. return loadProfile();
  75. }, [loadProfile]);
  76. return {
  77. profile,
  78. loading,
  79. updating,
  80. uploading,
  81. update,
  82. upload,
  83. refresh,
  84. };
  85. }