엑시오스는 비동기를 더 편하게 처리하는 라이브러리이다. node.js에서 제공. 라우터처럼.
엑시오스 설치
npm add axios
엑시오스
Promise=axios.get(요청주소)
1.이벤트 클릭시 처리하기(fetch와 거의 같음)
json으로 parsing을 안해도 된다! fetch와의 차이.
비동기는 순서를 보장하지 않는다.
비동기가 3개가 있다고 할 때, 3이 2의 데이터를 필요로 하고, 2가 1의 데이터를 필요로 한다고 할 때, 문제가 생긴다.
//순서를 보장하지 않음
const handleClick = () => {
axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
.then(response => {
console.log(response.data)
console.log(1);
});
// .then(response=>setData(response.data));
console.log(2);
axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/by.json')
.then(response => {
console.log(response.data)
console.log(3)
});
console.log(4);
axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hello.json')
.then(response => {
console.log(response.data)
console.log(5)
});
console.log(6);
}
콘솔창 출력이 246이 먼저, 이후 135. but 순서는 보장되지 않는다. 바뀔수도있다.
원하는 순서대로 만드려면...
//순서를 보장받고 싶다면?
const handleClick = () => {
axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
.then(response => {
console.log(response.data)
console.log(1);
axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/by.json')
.then(response => {
console.log(response.data)
console.log(3)
axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hello.json')
.then(response => {
console.log(response.data)
console.log(5)
});
});
})
}
이런식으로
비동기의 .then 안에 비동기, 그 비동기의 .then안에 비동기
->콜백 지우기
구문을 보면 알 수 있듯, fetch와 달리 then이 한번만 사용되었다.->json객체로 parsing을 안해도 된다.
Axios는 Promise를 반환한다.
'React' 카테고리의 다른 글
230120 React News API 사용 (0) | 2023.01.20 |
---|---|
230120 React Axios async(), await() (0) | 2023.01.20 |
230120 React Ajax로 외부 데이터 통신하기 (0) | 2023.01.20 |
230119 React 라우터 useNavigate()훅, Navigate컴포넌트 (1) | 2023.01.19 |
230119 React 라우터 헤더 태그 분리하기 (0) | 2023.01.19 |