React에서 서버 상태를 가져오고, 캐싱하고, 동기화하고, 업데이트할 수 있는 라이브러리. 비동기 로직을 쉽게 처리할 수 있다.
function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action.payload.userId);
yield put({type: "USER_FETCH_SUCCEEDED", user: user});
} catch (e) {
yield put({type: "USER_FETCH_FAILED", message: e.message});
}
}
...
// redux
const initialState = {
isLoading: false,
user: ...
}
...
const { isLoading, error, data } = useQuery('user', fetcher, options);
QueryKey
에 따라서 캐싱 처리. 캐싱된 쿼리의 QueryKey
와 동일한 요청을 하는 쿼리는 같은 것으로 인식하여 fetch하지 않고 캐싱된 쿼리 그대로 사용.QueryKey
는 user// src/app.tsx
const App = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
cacheTime: 1000 * 60 * 60 * 24,
staleTime: 1000 * 60,
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
},
},
});
return (
<QueryClientProvider client={queryClient}>
{element}
</QueryClientProvider>
);
}
export default App;
getClient()
를 호출함으로써 접근할 수 있다.https://react-query.tanstack.com/reference/QueryClient#queryclientcancelqueries
const { mutate } = useMutation(mutationFn, { options ... })
mutate(variables, { onSuccess, onSettled, onError })
mutationFn
을 trigger하는 함수이다.mutationFn
에 넘겨준다.mutationFn
이 실행되기 전에 먼저 실행할 함수. mutationFn
의 객체 인자와 동일한 값을 넘겨준다.mutationFn
이 성공했을 때 실행mutationFn
이 실패했을 때 실행useMutation
이 성공할 것이라 가정하고 미리 화면의 UI를 바꾸고 나서, 결과에 따라 확정 / 롤백하는 방식.
const queryClient = useQueryClient()
useMutation(updateTodo, {
onMutate: async newTodo => {
await queryClient.cancelQueries('todos')
// 기존 데이터
const previousTodos = queryClient.getQueryData('todos')
// 캐싱 데이터 업데이트
queryClient.setQueryData('todos', old => [...old, newTodo])
return { previousTodos }
},
onError: (err, newTodo, context) => {
// 에러 시 캐싱 데이터 롤백
queryClient.setQueryData('todos', context.previousTodos)
},
})
onMutate에서 return된 값은 onError와 onSettled의 context에 전달된다. 만약 함수가 return 된다면, 다음과 같이 사용할 수 있다.
onMutate: async newTodo => {
...
return () => queryClient.setQueryData('todos', previousTodos)
}
onError: (err, newTodo, rollback) => {
if (rollback) rollback();
}
onMutate에서 데이터 업데이트 후 에러 시 롤백하는 방식이 아니고, onSuccess에서 업데이트 해주는 것도 가능하다. (이러면 optimistic update가 아닌가..?)
https://react-query.tanstack.com/guides/optimistic-updates#_top