Skip to content

Feat: Week7/nonshaman-m2#71

Open
nonshaman wants to merge 16 commits into
mainfrom
week7/nonshaman-m2
Open

Feat: Week7/nonshaman-m2#71
nonshaman wants to merge 16 commits into
mainfrom
week7/nonshaman-m2

Conversation

@nonshaman
Copy link
Copy Markdown
Collaborator

📚 주차 / 미션

  • 7주차 2번째 미션

📌 작업 내용

  • 낙관적 업데이트(OptimisticUpdate)를 사용하여 UI를 즉시 업데이트 하는 기능 구현

✨ 상세 작업 내용

  • useMutation의 onMutate, onError을 활용

📸 스크린샷

스크린샷 2026-05-17 16 43 46

✅ 체크리스트

  • [o] 기능 정상 작동 확인
  • [o] 불필요한 주석 삭제
  • [o] 해당 주차 키워드 내용 이해

Copy link
Copy Markdown
Collaborator

@yewon20804 yewon20804 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7주차 미션2 확인했습니다 ! 낙관적 업데이트 개념을 이해하고 좋아요 기능을 구현해보는거였는데요! 😀
코멘트 확인 부탁드립니다 ~


1. useDeleteLike.ts / useAddLike.ts — onMutate에서 cancelQueries 누락

// ❌ 현재 
onMutate: async (lpId) => {
  const previousData = queryClient.getQueryData(['likes', lpId]);
  queryClient.setQueryData(['likes', lpId], (old) => ...);
  return { previousData };
},

// ✅ 수정
onMutate: async (lpId) => {
  await queryClient.cancelQueries({ queryKey: ['likes', lpId] });

  const previousData = queryClient.getQueryData(['likes', lpId]);
  queryClient.setQueryData(['likes', lpId], (old) => ...);
  return { previousData };
},

cancelQueries 없이 바로 setQueryData를 하면, 기존 요청 응답이 나중에 도착하면서 방금 바꾼 값이 다시 덮어써질 수 있어서 먼저 취소해두는 게 안전할 것 같습니다!


2. useDeleteLike.ts / useAddLike.ts — onError에서 rollback 처리 필요

// ❌ 현재 
onError: (error) => {
  console.error(error);
},

// ✅ 수정
onError: (error, lpId, context) => {
  // 실패하면 이전 데이터로 복구!
  if (context?.previousData) {
    queryClient.setQueryData(['likes', lpId], context.previousData);
  }
},

서버 요청이 실패했을 때 UI를 원래대로 되돌려야 합니다 ! onMutate에서 반환한 context를 사용하시면 좋습니다 😀


3. useDeleteLike.ts / useAddLike.ts — onSettled에서 invalidateQueries 필요

// ❌ 현재 

// ✅ 수정
onSettled: (data, error, lpId) => {
  // 성공/실패 모두 서버 최신 데이터로 갱신
  queryClient.invalidateQueries({ queryKey: ['likes', lpId] });
},

낙관적 업데이트를 사용하더라도 실제 서버 상태와 달라질 수 있어서, onSettled에서 invalidateQueries로 한 번 최신 데이터를 다시 가져와주는 게 안전할 것 같습니다!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants