axios 요청 보낼 때 에러를 catch 하면 modal 창을 띄우게 하고 싶어 만든 코드입니다. 다만 제가 리액트가 처음이다 보니 이것보다 더 좋은 방법을 찾지 못해 고민하고 있습니다.
const axiosLib = (config, succHandler, errHandler) => {
/* config 데이터 형태
config = {
url:url,
method:method,
data:data
}
*/
axios(config)
.then(response => {
console.log(response.data.data);
succHandler(response.data);
})
.catch(error => {
if(errHandler !== undefined) {
errHandler(error);
}
})
}
axiosLib.js입니다. 요청정보인 config와 성공시 실행할 익명함수, 실패 시 실행할 익명함수를 각각 succHandler, errHandler를 파라미터로 받습니다.
const test = () => {
const [alertInfo, setAlertInfo] = useState({})
useEffect(() => {
config = {
url:'/users',
method:'get'
}
axiosLib(config, (data) => {
console.log(data)
}, (err) => {
setAlertInfo({
show:true,
title:'처리중 오류 발생',
msg:err.msg
})
})
}, [])
return (
<>
<div>
Hello World!
</div>
<CModal
show={alertInfo.show}
onClose={() => setAlertInfo({show:false})}
>
<CModalHeader>
<CModalTitle>{alertInfo.title}</CModalTitle>
</CModalHeader>
<CModalBody>
{alertInfo.msg}
</CModalBody>
<CModalFooter>
<button onClick={() => setAlertInfo({show:false})}>닫기</button>
</CModalFooter>
</CModal>
</>
)
}
test.js입니다. CModal로 시작하는 요소는 제가 사용중인 템플릿 라이브러리 컴포넌트입니다.
일단 이렇게 해서 뜨긴 합니다만 문제는 모든 페이지에서 CModal을 비롯한 여러 컴포넌트를 호출해야 한다는 점입니다. 따로 Alert 라는 이름으로도 빼놨지만 파라미터를 많이 주는 것은 별반 다르지 않았습니다.
axiosLib 코드에서 띄워준다면 axios 요청을 보낼 때 에러가 발생할 때마다 modal을 보여줄 수 있을텐데 그렇게 할 수 있는 방법이 있을까요?