LikeAvatar.tsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { useEffect, useState } from "react";
  2. import type {
  3. ILikeListResponse,
  4. ILikeRequest,
  5. ILikeResponse,
  6. TLikeType,
  7. } from "../../api/like";
  8. import { get, post } from "../../request";
  9. import type { IUser } from "../auth/User";
  10. import type { IDataType } from "./WatchAdd";
  11. import EditableAvatarGroup from "./EditableAvatarGroup";
  12. interface IWidget {
  13. resId?: string;
  14. resType?: string;
  15. type?: TLikeType;
  16. }
  17. const LikeAvatar = ({ resId, resType, type }: IWidget) => {
  18. const [data, setData] = useState<IUser[]>();
  19. useEffect(() => {
  20. if (!resId) {
  21. return;
  22. }
  23. const url = `/v2/like?view=target&target_id=${resId}&type=${type}`;
  24. console.info("api request", url);
  25. get<ILikeListResponse>(url).then((json) => {
  26. console.info("api response", json);
  27. if (json.ok) {
  28. setData(json.data.rows.map((item) => item.user));
  29. }
  30. });
  31. }, [resId, type]);
  32. return (
  33. <>
  34. <EditableAvatarGroup
  35. users={data}
  36. onFinish={async (values: IDataType) => {
  37. if (!resId || !resType) {
  38. console.error("no resId or resType", resId, resType);
  39. return;
  40. }
  41. const update: ILikeRequest = {
  42. type: "watch",
  43. target_id: resId,
  44. target_type: resType,
  45. user_id: values.user_id,
  46. };
  47. const url = `/v2/like`;
  48. console.info("watch add api request", url, values);
  49. const add = await post<ILikeRequest, ILikeResponse>(url, update);
  50. console.debug("watch add api response", add);
  51. setData((origin) => {
  52. if (origin) {
  53. return [...origin, add.data.user];
  54. } else {
  55. return [add.data.user];
  56. }
  57. });
  58. }}
  59. />
  60. </>
  61. );
  62. };
  63. export default LikeAvatar;