REACT/RTK

[RTK] onQueryStarted, updateQueryData

user-anonymous 2022. 3. 27. 16:50
728x90

updateQueryData는 기존에 존재하는 패치작업을 쉽게 수행할 수 있다.  나같은 경우에는 드래그앤 드랍을 통해 order처리를 할 때 사용하게 됐다.  큰 틀은 이렇다.

 

A,B,C라는 objectList에서 C를 A로 옮길 경우 order를 변환하는 API를 호출한다. 물론 update는 되지만 깜박이는 현상이 있었다. 

 

문제 상황

1. C를 A로 드래그앤 드랍   : [C, A, B]

2. 업데이트 API가 호출 됨 

3. 아직 API로부터 결과를 받지 않아 기존 list state때문에 다시 원복됨 [ A, B, C ]

4. 업데이트 된 API 결과를 다시 받아 LIST UPDATE함 [C,A,B]

 

그리하여 1과 3 사이 state때문에 깜박이는 현상이 존재했던 것이다. 이를 해결하기 위해서는 2번인 api를 호출할 때 state를 같이 update를 해준다면 이 현상이 해소된다. 이를 해소하기 위해 사용된 것이 rtk에서 제공해주는 onQueryStarted와 updateQueryData였다. 

 

  orderApi: build.mutation({
      query: data => ({ url: '/test/order', data }),
      invalidatesTags: [{ type: 'OBJECT', id: 'LIST' }],
      async onQueryStarted({ updateList }, { dispatch, queryFulfilled, getState }) {
        const patchResult = dispatch(
          testAPi.util.updateQueryData('objectList', { id }, draft => {
            for (const update of updateList) {
              const id = update.id;
              const orderIdx = update.order;
              const index = draft.findIndex(test => test.id === id);
              draft[index].order = orderIdx;
            }
            draft = draft.sort((lhs, rhs) => lhs.order - rhs.order);
          }),
        );
        try {
          await queryFulfilled;
        } catch {
          patchResult.undo();
        }
      },
    }),

 

 

onQueryStarted

onQueryStarted는 mutation이 실행된 후에도 캐시 데이터에 업데이트를 수행하려 할 경우 사용한다. 사용자가 변경 요청을 보내 진행중인 동안에 변경사항이 즉각적인 변화를 주고싶을 때 주는 패턴이라고 한다.

 

Optimistic Updates​
When you wish to perform an update to cache data immediately after a mutation is triggered, you can apply an optimistic update. This can be a useful pattern for when you want to give the user the impression that their changes are immediate, even while the mutation request is still in flight.
The core concepts for an optimistic update are:
1. when you start a query or mutation, onQueryStarted will be executedyou manually update the cached data by dispatching api.util.updateQueryData within onQueryStartedthen,
3. in the case that queryFulfilled rejects:you roll it back via the .undo property of the object you got back from the earlier dispatch,ORyou invalidate the cache data via api.util.invalidateTags to trigger a full re-fetch of the data

 

1. onQueryUpdate는 쿼리가 시작할 때 실행된다.

2. api.util.updateQueryData에서 디스패치하여 캐시된 데이터를 업데이트해준다.

3. queryFulFilled 거부될 경우 (거부 : .undo를 통해 롤백을 사용한다. )

 

onQueryStarted( arg, {dispatch,queryFulfilled})

 

arg : api가 요청될때 전달되는 함수 인자이다. 

두번째 인자는 thunkApi에서 제공해주는 메소드가 해당된다. 이는 disaptch, getState, extra, requestId가 포함된다.

하지만 이외에도 Promise가 queryFulfilled를 부른다. 이 Promise는 요청된 리턴 값을 resolve 또는 요청이 rejected될

 

 

--- 참고

 

nicedoc.io

pretty README as service

nicedoc.io

 

 

728x90
반응형