FollowButton.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use client';
  2. import { useEffect, useState } from 'react';
  3. import { fetchApi } from '@/lib/utils/client';
  4. import useAuth from '@/hooks/useAuth';
  5. import { FollowToggleResponse, IsFollowingResponse } from '@/types/account/follow';
  6. import '@/app/styles/follow-button.scss';
  7. type Props = {
  8. memberSID: string;
  9. initialFollowing?: boolean;
  10. onChange?: (isFollowing: boolean, followerCount: number) => void;
  11. className?: string;
  12. };
  13. export default function FollowButton({ memberSID, initialFollowing, onChange, className }: Props) {
  14. const { isAuthenticated, member, loginCheck } = useAuth();
  15. const [isFollowing, setIsFollowing] = useState<boolean>(initialFollowing ?? false);
  16. const [loading, setLoading] = useState<boolean>(false);
  17. const [hydrated, setHydrated] = useState<boolean>(initialFollowing !== undefined);
  18. const isSelf = member?.sid === memberSID;
  19. useEffect(() => {
  20. if (initialFollowing !== undefined) {
  21. return;
  22. }
  23. if (!isAuthenticated || isSelf) {
  24. setHydrated(true);
  25. return;
  26. }
  27. fetchApi<IsFollowingResponse>('/api/member/follow/check', {
  28. method: 'POST',
  29. body: { sids: [memberSID] },
  30. silent: true
  31. }).then((res) => {
  32. setIsFollowing(res.data?.map?.[memberSID] ?? false);
  33. }).catch(() => {}).finally(() => {
  34. setHydrated(true);
  35. });
  36. }, [isAuthenticated, memberSID, isSelf, initialFollowing]);
  37. const handleClick = async () => {
  38. if (!loginCheck()) {
  39. return;
  40. }
  41. if (loading || isSelf) {
  42. return;
  43. }
  44. setLoading(true);
  45. try {
  46. const res = await fetchApi<FollowToggleResponse>(`/api/member/${memberSID}/follow`, {
  47. method: 'POST',
  48. silent: true
  49. });
  50. if (res.success && res.data) {
  51. setIsFollowing(res.data.isFollowing);
  52. onChange?.(res.data.isFollowing, res.data.followerCount);
  53. }
  54. } catch (err) {
  55. console.error('Follow toggle failed:', err);
  56. } finally {
  57. setLoading(false);
  58. }
  59. };
  60. if (isSelf) {
  61. return null;
  62. }
  63. const label = !hydrated ? '···' : (isFollowing ? '팔로잉' : '팔로우');
  64. const modifier = isFollowing ? 'follow-button--following' : 'follow-button--default';
  65. return (
  66. <button
  67. type="button"
  68. onClick={handleClick}
  69. disabled={loading || !hydrated}
  70. className={`follow-button ${modifier} ${className ?? ''}`.trim()}
  71. aria-pressed={isFollowing}
  72. >
  73. {label}
  74. </button>
  75. );
  76. }