aotoyae

[React] TanStack Query : Optimistic Updates 옵티미스틱 업데이트 본문

React

[React] TanStack Query : Optimistic Updates 옵티미스틱 업데이트

aotoyae 2024. 8. 6. 22:46

 

 

💡 사용자에게 빠른 피드백을 제공하도록 하는 옵티미스틱(낙관적) 업데이트

 

어떤 요청이 있었을 때 서버 요청이 정상적으로 잘 될거란 가정 하에 UI 를 먼저 변경하고, 그 후 요청을 보내는 방식!

서버 요청이 실패한다면 UI 는 다시 원상복구(revert / roll back) 된다.

좋아요를 먼저 표시

 

  const addMutation = useMutation({
    mutationFn: addTodo, // 실행 순서 (2)
    // onSuccess: () => { ** 기존 방식 성공하면 무효화
    //   queryClient.invalidateQueries(["todos"]);
    // },
    onMutate: async (newTodo) => { // 실행 순서 (1)
      console.log("onMutate 호출");
      await queryClient.cancelQueries({ queryKey: ["todos"] }); // 가지고 오고 있던 쿼리 취소

      const previousTodos = queryClient.getQueryData(["todos"]); // 현재 데이터 백업

      queryClient.setQueryData(["todos"], (old) => [...old, newTodo]); // 클라이언트 사이드에서 데이터 갱신

      return { previousTodos };
    },
    onError: (err, newTodo, context) => { // 실행 순서 (3) ** 에러라면
      console.log("onError");
      console.log("context:", context);
      queryClient.setQueryData(["todos"], context.previousTodos); // 백업했던 데이터로 다시 셋
    },
    onSettled: () => { // 실행 순서 (4) ** 성공했다면
      console.log("onSettled");
      queryClient.invalidateQueries({ queryKey: ["todos"] }); // 무효화
    },
  });

 

 

 

🔗 https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates

 

Optimistic Updates | TanStack Query React Docs

React Query provides two ways to optimistically update your UI before a mutation has completed. You can either use the onMutate option to update your cache directly, or leverage the returned variables to update your UI from the useMutation result. Via the

tanstack.com