👾 예제
import { useIsFetching } from 'react-query';
export function Loading(): ReactElement {
const isFetching = useIsFetching();
const display = isFetching ? 'inherit' : 'none';
return (
<Spinner
thickness="4px"
speed="0.65s"
emptyColor="olive.200"
color="olive.800"
role="status"
position="fixed"
zIndex="9999"
top="50%"
left="50%"
transform="translate(-50%, -50%)"
display={display}
>
<Text display="none">Loading...</Text>
</Spinner>
);
}
👾 toast를 사용한 에러처리 예제
// treatments.tsx
import { useQuery } from 'react-query';
import { useCustomToast } from '../../app/hooks/useCustomToast';
async function getTreatments(): Promise<Treatment[]> {
const { data } = await axiosInstance.get('/treatments');
return data;
}
// treatments 데이터 반환하는 훅!
export function useTreatments(): Treatment[] {
const toast = useCustomToast(); // toast custom hook
const fallback = [];
const { data = fallback } = useQuery(queryKeys.treatments, getTreatments, {
onError: (error) => {
const title =
error instanceof Error
? error.message
: 'error connecting to the server';
toast({ title, status: 'error' });
},
});
return data;
}
{
// 각각 useQuery, useMutaion에 기본값을 지정할 수 있다.
queries: { useQuery options },
mutaions: { useMutaion options },
}
👾 toast를 사용한 에러처리 예제
// queryClient.tsx
import { createStandaloneToast } from '@chakra-ui/react';
import { QueryClient } from 'react-query';
import { theme } from '../theme';
const toast = createStandaloneToast({ theme });
function queryErrorHandler(error: unknown): void {
const title =
error instanceof Error ? error.message : 'error connecting to server';
// toast가 점차 쌓이기 때문에 toast가 중복되지 않도록 함
toast.closeAll();
toast({ title, status: 'error', variant: 'subtle', isClosable: true });
}
export const queryClient = new QueryClient({
// 중앙 집중식 오류 핸들러 지정
defaultOptions: {
queries: {
onError: queryErrorHandler,
},
},
});