Notice
Recent Posts
Recent Comments
Link
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Tags
more
Archives
Today
Total
관리 메뉴

juni

좋아요 상태 관리 개선 본문

프로젝트/WelKo

좋아요 상태 관리 개선

juni_shin 2025. 3. 10. 21:50

기존 zustand에서 단일로 관리되던 좋아요를 복수로 관리하여 투어별 좋아요를 관리하여

메인페이지, 상세페이지, 마이페이지에서 적용되도록 Store 및 컴포넌트 코드 개선

-> 좋아요가 필요한 컴포넌트 로직 단순화로 가독성 상승 

 

기존 Store 코드

import { create } from 'zustand';
import axios from 'axios';

interface LikeState {
  liked: boolean;
  fetchLikeStatus: (postId: string, userId: string) => Promise<void>;
  toggleLike: (postId: string, userId: string) => Promise<void>;
}

export const useLikeStore = create<LikeState>((set) => ({
  liked: false,

  fetchLikeStatus: async (postId: string, userId: string) => {
    try {
      const response = await axios.get(`/api/detail/likes/${postId}`, {
        headers: { 'user-id': userId }
      });
      set({ liked: response.data.exists });
    } catch (error) {
      console.error('Error fetching like status:', error);
    }
  },

  toggleLike: async (postId: string, userId: string) => {
    try {
      const { liked } = useLikeStore.getState();

      if (liked) {
        await axios.delete(`/api/detail/likes/${postId}`, {
          data: { userId }
        });
        set({ liked: false });
      } else {
        await axios.post(`/api/detail/likes/${postId}`, { userId });
        set({ liked: true });
      }
    } catch (error) {
      console.error('Error toggling like:', error);
    }
  }
}));

 

개선 Store 코드

import { create } from 'zustand';
import axios from 'axios';

interface LikeState {
  likedPosts: { [key: string]: boolean };
  fetchLikeStatus: (postId: string, userId: string) => Promise<void>;
  toggleLike: (postId: string, userId: string) => Promise<void>;
  isLiked: (postId: string) => boolean;
}

export const useLikeStore = create<LikeState>((set, get) => ({
  likedPosts: {},

  isLiked: (postId: string) => {
    return get().likedPosts[postId] || false;
  },

  fetchLikeStatus: async (postId: string, userId: string) => {
    try {
      const response = await axios.get(`/api/detail/likes/${postId}`, {
        headers: { 'user-id': userId }
      });
      set((state) => ({
        likedPosts: {
          ...state.likedPosts,
          [postId]: response.data.exists
        }
      }));
    } catch (error) {
      console.error('Error fetching like status:', error);
    }
  },

  toggleLike: async (postId: string, userId: string) => {
    try {
      const currentLikeStatus = get().likedPosts[postId];

      set((state) => ({
        likedPosts: {
          ...state.likedPosts,
          [postId]: !currentLikeStatus
        }
      }));

      if (currentLikeStatus) {
        await axios.delete(`/api/detail/likes/${postId}`, {
          data: { userId }
        });
      } else {
        await axios.post(`/api/detail/likes/${postId}`, { userId });
      }
    } catch (error) {
      set((state) => ({
        likedPosts: {
          ...state.likedPosts,
          [postId]: !state.likedPosts[postId]
        }
      }));
      console.error('Error toggling like:', error);
    }
  }
}));

'프로젝트 > WelKo' 카테고리의 다른 글

채팅 성능 테스트  (0) 2025.03.12
WelKo_개선 ( 채팅 )  (0) 2024.08.26
WelKo PDF  (0) 2024.08.21
WelKo_프로필 수정  (0) 2024.08.20
WelKo_Alert UI 개선  (0) 2024.08.20