React Query를 통한 좋아요 likeCount 실시간 반영

Created
2023/11/27 01:51
담당자

배경

사용자가 게시물의 상태를 변경했을때의 새로고침 없이 결과를 실시간으로 확인할 수 있어야한다.

문제점

React query의 mutation 함수를 비동기적으로 실행해, 게시물 상태변경을 반영한 후, 성공시 다시 데이터 fetch를 통한 실시간 반영을 해야한다. mutation 함수가 성공했을 때 실행되는 onSuccess에서 다시 데이터를 fetch 해오도록 하고, useQuery 함수에는 unique한 키값을 넘겨줬다.(실패)
// Mutation 함수가 Success 되는 시점에서 Refetch export function useCommunityLikeMutation(postId: number) { const { refetch: allListRefetch } = useCommunityPostQuery(); return useMutation(() => postCommunityLikeAxios(accessToken, postId), { onError: (err) => { console.log(err); }, onSuccess: async () => { refetchNew = `like${Date.now()}`; await allListRefetch(); console.log('좋아요 상태 변경 반영됨'); }, }); }
TypeScript
복사
// 쿼리함수에 refetchNew 를 키값으로 줌 let refetchNew = ''; export function useCommunityPostQuery(word?: string, sort?: SortType, order?: OrderType, size?: number, postType?: postType | 'ALL') { return useInfiniteQuery(['Community',refetchNew, word, sort, order, postType], ({ pageParam = 0 }) => getCommunityPostAxios(accessToken, word, sort, order, pageParam, size, postType), { getNextPageParam: (prevData, allPages) => { const lastPage = prevData.last; const nextPage = allPages.length + 1; return lastPage ? undefined : nextPage; }, staleTime: 30000, }); }
TypeScript
복사

해결

mutation 함수가 실행되는(좋아요 버튼 onClick)시점으로 돌아와서, Mutation 함수가 useState 상태를 업데이트하는 경우, useEffect를 사용해서 isSuccess 상태가 업데이트된 후, Refetch 하기 사실 그냥 mutate함수가 아닌 mutateAsync 함수를 사용하면 바로 해결될 일이지만 이때는 그 존재를 몰라서 직접 구현했습니다……
const [likeSuccess, setLikeSuccess] = useState(false); const handleLike = () => { likeMutate(); setLikeSuccess(true); }; useEffect(() => { if (likeSuccess) { console.log(isSuccess); if (refetch && isSuccess) { refetch(); } } }, [likeSuccess, refetch, isSuccess]); return ( <div className="flex items-center gap-2" onClick={async (e) => { e.stopPropagation(); handleLike(); }} > {likeCount} </div> )
TypeScript
복사