
보통 Axios는 Promise객체를 반환하기 때문에 에러처리는 catch를 통해 할 수 있습니다.
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
useQuery와 Axios를 함께 처리하게 되면 catch를 통해 에러처리 하지 않습니다.
useQuery는 내부적으로 Promise객체를 사용하여 처리한 후에 추상화한 결과를 일반 객체로 반환합니다.
따라서 useQuery와 함께 Axios를 사용할때에는 catch를 사용하지 않고 useQuery에서 반환되는 객체의 프로퍼티나 옵션값을 통해 처리할 수 있습니다.
useQuery에서 반환된 객체에는 error와 isError라는 프로퍼티가 포함됩니다. 이 프로퍼티는 비동기 작업이 실패한 경우 해당 에러 정보를 담고 있습니다. 따라서, 객체의 error와 isError 프로퍼티를 확인하여 에러를 처리할 수 있습니다.

import { useQuery } from 'react-query';
import axios from 'axios';
const fetchData = async () => {
const response = await axios.get('/api/data');
return response.data;
};
const MyComponent = () => {
const { data, error, isError } = useQuery('myQueryKey', fetchData);
if (isError) {
console.error('요청 실패:', error);
// 에러 처리 로직 작성
}
// 나머지 렌더링 로직 작성
};
useQuery의 옵션 객체를 활용하여 onError 콜백 함수를 정의할 수 있습니다. 이 콜백 함수는 비동기 작업에서 에러가 발생한 경우 호출되며, 해당 에러를 처리할 수 있습니다.

import { useQuery } from 'react-query';
import axios from 'axios';
const fetchData = async () => {
const response = await axios.get('/api/data');
return response.data;
};
const MyComponent = () => {
const { data } = useQuery('myQueryKey', fetchData, {
onError: (error) => {
console.error('요청 실패:', error);
// 에러 처리 로직 작성
}
});
// 나머지 렌더링 로직 작성
};