Skip to content

Comments

fix: Optimistic Update 코드 오류 수정#39

Merged
ssi02014 merged 3 commits intossi02014:mainfrom
zzzRYT:main
Feb 4, 2025
Merged

fix: Optimistic Update 코드 오류 수정#39
ssi02014 merged 3 commits intossi02014:mainfrom
zzzRYT:main

Conversation

@zzzRYT
Copy link
Contributor

@zzzRYT zzzRYT commented Feb 4, 2025

#38
사용자 경험(UX)을 올려주는 Optimistic Update(낙관적 업데이트)

const useAddSuperHeroData = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutateFn: addSuperHero,
    onMutate: async (newHero: any) => {
      await queryClient.cancelQueries(["super-heroes"]);

      // 이전 값
      const previousHeroData = queryClient.getQueryData(["super-heroes"]);

      // 새로운 값으로 낙관적 업데이트 진행
      queryClient.setQueryData(["super-heroes"], (oldData: any) => {
        return {
          ...oldData,
          data: [
            ...oldData.data,
            { ...newHero, id: oldData?.data?.length + 1 },
          ],
        };
      });

      // 값이 들어있는 context 객체를 반환
      return { previousHeroData };
    },
    // mutation이 실패하면 onMutate에서 반환된 context를 사용하여 롤백 진행
    onError(error, hero, context: any) {
      queryClient.setQueryData(["super-heroes"], context.previousHeroData);
    },
    // 오류 또는 성공 후에는 항상 refetch
    onSettled() {
      queryClient.invalidateQueries(["super-heroes"]);
    },
  });
};

queryClient.getQueryData와, queryClient.invalidateQueries 에 들어가는 queryKey 값 에 대한 오류를 수정했습니다.

const useAddSuperHeroData = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutateFn: addSuperHero,
    onMutate: async (newHero: any) => {
      await queryClient.cancelQueries(["super-heroes"]);

      // 이전 값
      const previousHeroData = queryClient.getQueryData({ queryKey: ["super-heroes"] });

      // 새로운 값으로 낙관적 업데이트 진행
      queryClient.setQueryData(["super-heroes"], (oldData: any) => {
        return {
          ...oldData,
          data: [
            ...oldData.data,
            { ...newHero, id: oldData?.data?.length + 1 },
          ],
        };
      });

      // 값이 들어있는 context 객체를 반환
      return { previousHeroData };
    },
    // mutation이 실패하면 onMutate에서 반환된 context를 사용하여 롤백 진행
    onError(error, hero, context: any) {
      queryClient.setQueryData(["super-heroes"], context.previousHeroData);
    },
    // 오류 또는 성공 후에는 항상 refetch
    onSettled() {
      queryClient.invalidateQueries({ queryKey: ["super-heroes"] });
    },
  });
};

Copy link
Owner

@ssi02014 ssi02014 left a comment

Choose a reason for hiding this comment

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

LGTM 👍

@ssi02014 ssi02014 merged commit 16937cc into ssi02014:main Feb 4, 2025
@ssi02014 ssi02014 linked an issue Feb 4, 2025 that may be closed by this pull request
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.

낙관전 업데이트(Opimistic Update) v5 수정 내용 적용

2 participants