가수면
[React Query] 비동기 취소하기 본문
1. useQuery 두번째 인자로 요청하는 fetch함수에 signal을 실어서 보냄
export function useUser(): UseUser {
const queryClient = useQueryClient();
const { data: user } = useQuery(
queryKeys.user,
({ signal }) => getUser(user, signal),
{
initialData: getStoredUser,
onSuccess: (received: User | null) => {
if (!received) {
clearStoredUser();
} else {
setStoredUser(received);
}
},
},
);
2.config에 signal을 추가
async function getUser(
user: User | null,
signal: AbortSignal,
): Promise<User | null> {
if (!user) return null;
const { data }: AxiosResponse<{ user: User }> = await axiosInstance.get(
`/user/${user.id}`,
{
headers: getJWTHeader(user),
signal,
},
);
return data.user;
}
심화?
export function usePatchUser(): (newData: User | null) => void {
const { user, updateUser } = useUser();
const toast = useCustomToast();
const queryClient = useQueryClient();
// TODO: replace with mutate function
const { mutate: patchUser } = useMutation(
(newUserData: User) => patchUserOnServer(newUserData, user),
{
onMutate: async (newData: User | null) => {
queryClient.cancelQueries(queryKeys.user);
const previousUserData: User = queryClient.getQueryData(queryKeys.user);
updateUser(newData);
return { previousUserData };
},
onError: (error, newData, context) => {
if (context.previousUserData) {
updateUser(context.previousUserData);
toast({
title: '압뎃 실패; 이전값으로 되돌림',
status: '경고',
});
}
},
onSuccess: (userData: User | null) => {
if (user) {
updateUser(userData);
toast({
title: 'User updated!',
status: '성공',
});
}
},
//쿼리가 무효화되면 리페치를 실행해 서버 데이터와 클라이언트 데이터를 동일하게 해줌
onSettled: () => {
queryClient.invalidateQueries(queryKeys.user);
},
},
);
}
'React > 라이브러리' 카테고리의 다른 글
[Framer Motion] Framer Motion (0) | 2023.03.28 |
---|---|
React beautiful dnd (0) | 2023.03.23 |
[React Query] 인증 (0) | 2023.01.11 |
[React Query] useInfiniteQuery (0) | 2023.01.09 |
Recoil (0) | 2023.01.09 |
Comments