React axios를 활용하여 api를 호출하면 자바스크립트의 ajax처럼 서버와 비동기 통신을 하는데,
딜레이 시간 동안 로딩 화면 혹은 로딩 모달을 띄우는 방법에 대해 소개드리겠습니다.
저는 비동기 통신 딜레이 시간 동안 스피너를 띄우기 위해 react-loading 라이브러리를 사용했습니다.
yarn 혹은 npm 을 통해 다운 받아주시면 됩니다.
yarn add react-loading
메시지와 함께 스피너를 화면 중앙에 띄워주기 위해 저는 아래와 같이 코드를 작성했습니다.
<ReactLoading> 태그에 주목해주세요.
Loader.js
import React from 'react'; | |
import ReactLoading from 'react-loading'; | |
function Loader({type, color, message}) { | |
return ( | |
<div class="contentWrap"> | |
<div style={{ | |
position: "fixed", | |
top: "50%", | |
left: "50%", | |
transform: "translate(-50%, -50%)" | |
}}> | |
<h2>{message}</h2> | |
<h2>창을 닫지 말아주세요.</h2> | |
<ReactLoading | |
type={type} | |
color={color} | |
height={'80%'} | |
width={'80%'} /> | |
</div> | |
</div> | |
); | |
} | |
export default Loader; |
* 저 같은 경우에는 별도 페이지를 만들었지만 html과 css를 다룰줄 아시는 분들은 Spinner 모달을 만들고 loading state가 true일 때 해당 모달을 띄우는 방법을 사용하셔도 됩니다!
이제 비동기 처리 함수인 axios 함수를 호출하는 자바스크립트 파일의 뼈대입니다.
해당 파일을 참고하여 적절하게 활용해주시면 됩니다!
axios에 대한 보다 자세한 설명은 아래 링크를 참고해주세요.
https://jaimemin.tistory.com/1407
React axios 사용 예시
React에서 Rest Api를 쉽게 호출하기 위해 axios 라이브러리를 사용하게 되었습니다. 화면을 Component 단위로 나누었고 Api를 호출할 때마다 header에 인증 권한인 Authorization을 함께 넣어줘야 했는데 예시
jaimemin.tistory.com
Main.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react';
import axios from 'axios';
import Loader from './Loader';
const [loading, setLoading] = useState(null);
const httpInstance = axios.create({
baseURL: [컨텍스트],
timeout: 30000,
headers: {
'content-type': 'application/json; charset=UTF-8',
},
withCredentials: true,
});
// 헤더에 인증 추가
httpInstance.defaults.headers.common.Authorization = `JWT TOKEN AUTHORIZATION`;
useEffect(() => {
const 호출할 함수 = async() => {
try {
setLoading(true);
await httpInstance.post(
'[API 주소]',
매개변수
).then((response) => {
respone에 대한 적절한 처리
})
} catch (e) {
에러에 대한 적절한 처리
}
setLoading(false);
}
선언한 함수 호출;
}, []);
// 로딩 시 Spinner 띄움
if (loading) return <Loader type="spin" color="RGB 값" message={적절한 메시지} />;
function Main() {
return (
);
}
export default Main;
import React, { useState } from 'react'; | |
import axios from 'axios'; | |
import Loader from './Loader'; | |
const [loading, setLoading] = useState(null); | |
const httpInstance = axios.create({ | |
baseURL: [컨텍스트], | |
timeout: 30000, | |
headers: { | |
'content-type': 'application/json; charset=UTF-8', | |
}, | |
withCredentials: true, | |
}); | |
// 헤더에 인증 추가 | |
httpInstance.defaults.headers.common.Authorization = `JWT TOKEN AUTHORIZATION`; | |
useEffect(() => { | |
const 호출할 함수 = async() => { | |
try { | |
setLoading(true); | |
await httpInstance.post( | |
'[API 주소]', | |
매개변수 | |
).then((response) => { | |
respone에 대한 적절한 처리 | |
}) | |
} catch (e) { | |
에러에 대한 적절한 처리 | |
} | |
setLoading(false); | |
} | |
선언한 함수 호출; | |
}, []); | |
// 로딩 시 Spinner 띄움 | |
if (loading) return <Loader type="spin" color="RGB 값" message={적절한 메시지} />; | |
function Main() { | |
return ( | |
); | |
} | |
export default Main; |
[react 버전] 16.13.1
[react-loading 버전] 2.0.3
[개발환경] VsCode, Windows
'[DEV] 기록' 카테고리의 다른 글
스프링 HTTP PUT/DELETE 메서드 차단하는 방법 (0) | 2020.05.17 |
---|---|
Ant Style Pattern 정리 (6) | 2020.05.17 |
백준 input 파일을 읽어오는 방법 (0) | 2020.05.16 |
react-select 커스텀 설정 (0) | 2020.05.07 |
react-datepicker 커스텀 설정 (7) | 2020.05.06 |