반응형
FrontEnd에서 Axios와 Promise.all()을 같이 사용하는 방법입니다.
서버와 통신하는 여러가지 방법중 한가지입니다.
먼저 가장 단순하게 사용하는 방법입니다.
./api.ts
import axios from "axios";
const baseUrl = "http://localhost:4000/api";
const api = axios.create({
baseURL: baseUrl,
headers: {}
});
export { api };
app.tsx
import { api } from "@/services/api";
import { useEffect, useState } from "react";
const App = () => {
useEffect(() => {
api.post("/main/find")
.then(res => {
console.log("OK");
})
.catch(err => console.log("Main Find Err", err));
api.post("/sub/find")
.then(res => {
console.log("OK");
})
.catch(err => console.log("Sub Find Err", err));
}, [])
return (
<div>TEST</div>
);
}
export default App;
위 내용이 가장 기본적인 방법이라고 생각합니다.
promise.all()과 함께 사용하기
const App = () => {
useEffect(() => {
const promises = [
api.post("/main/find"),
api.post("/sub/find")
];
Promise.all(promises)
.then(([mainRes, subRes]) => {
if (mainRes.data.code === "y") console.log("Main Res OK");
if (subRes.data.code === "y") console.log("Sub Res OK");
})
.catch(err => console.log("Err Res", err));
}, [])
return (
<div>TEST</div>
);
}
export default App;
이런식으로 promise.all()을 사용하면 브라우저와 서버 간의 왕복 횟수가 줄어들어 성능이 향상되고 리소스를 효율적으로 사용할 수 있습니다.
:: 물론 이런방법 말고도 서버쪽에서 해결 한다음 앞으로 보내주는 방법들도 존재합니다.
반응형
'React > NextJS' 카테고리의 다른 글
[ NextJS ] 잘못된 href가 라우터에 전달되었습니다. (0) | 2023.08.01 |
---|---|
[ NextJS ] Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node. (0) | 2023.07.20 |
[ NextJS ] router.push()를 통해 데이터 전달하기 (0) | 2023.07.13 |
[ NextJS ] 자식 컴포넌트와 부모 컴포넌트의 데이터 전달 (0) | 2023.06.16 |
[ NextJS ] 뒤로가기 방지하기 (2) | 2023.05.16 |