Ajax - Axios library
: 브라우저, Node.js를 위한 promise API를 활용하는 HTTP 비동기 통신 라이브러리
> axios setting
yarn add axios
npm install axios
GET / POST
GET : 서버에서 데이터를 받아온다.
axios.get('get요청할url')
.then (( ) => { 요청 성공시 실행코드 })
.catch ( ( ) => {요청 실패시 실행코드 })
> then 콜백함수 안에 파라미터를 추가하면 그게 받아온 데이터이다.
<button className="btn btn-primary" onClick={() => {
axios.get("https://codingapple1.github.io/shop/data22.json")
.then((result) => { console.log(result.data)})
.catch(() => {console.log("fail")});}}>
버튼
</button>
> async/await 사용
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
POST : 서버에 데이터를 보낸다.
로그인, 검색, 게시물 발행 등
> axios.post ( ' url ', 원하는 데이터 )
axios.post('데이터 전송할 url', { id: 'test', pw:'1234 })
.then((result)=> { } )
.catch(()=> {})
✔️ 우리가 요청한 데이터는 array / object가 아닌 JSON이라는 자료형이다.
서버와 통신할 때는 텍스트만 전송할 수 있어서, object에 따옴표가 다 쳐져있다. 이것이 JSON
JSON자료는 object로 변환을 해주어야한다. (JSON.parse() 소괄호안에 json자료 넣으면 따옴표제거된 object남음)
[
{
id: 3,
title: "Flowey",
content: "only 5 inches",
price: 120000
},
{
id: 4,
title: "Baby shoes",
content: "for less than 6",
price: 120000
},
{
id: 5,
title: "Red Herring",
content: "Born in France",
price: 120000
}
]
> fetch 함수도 비슷하게 사용할 수 있으나,
axios library는 따옴표 제거한 object로 자동으로 만들어줘서 더 편하다.
fetch는 안해줌.
axios.all
멀티요청
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
useEffect(() => {
axios
.all([
axios.get(`${API_ENDPOINT}/category/${newId}`),
axios.get(`${API_ENDPOINT}/category/${Number(match.params.id) + 1}`),
axios.get(`${API_ENDPOINT}/product/${Number(match.params.id) + 1}/all`),
axios.get('/data/List/title.json'),
axios.get('/data/List/sub.json'),
])
.then(
axios.spread((res1, res2, res3, res4, res5) => {
setSubProduct(res1.data.data);
setProduct(res2.data.data);
setProductAll(res3.data.data);
setMain([...res4.data]);
setSub([...res5.data]);
})
)
.catch(() => {
console.log('FAIL!!');
});
}, []);
Interceptor
then이나catch로 처리되기 전에 요청이나 응답을 가로챌 수 있다.
// 요청 인터셉터 추가
axios.interceptors.request.use(
function (config) {
// 요청을 보내기 전에 수행할 일
return config;
},
function (error) {
// 오류 요청을 보내기전 수행할 일
return Promise.reject(error);
});
// 응답 인터셉터 추가
axios.interceptors.response.use(
function (response) {
// 응답 데이터를 가공
return response;
},
function (error) {
// 오류 응답을 처리
return Promise.reject(error);
});
EX
- data 받아오기전 skeleton 추가
useEffect(() => {
const getData = async () => {
try {
dispatch(loadingActions.onLoading(true));
await axios
.get(
'url'
)
.then((res) => setData(res.data));
} catch (err) {
console.log(err);
}
dispatch(loadingActions.onLoading(false));
};
getData();
}, []);
- 즉시실행함수 IIFE
useEffect(() => {
(async () => {
await axios
.get(`https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`)
.then((res) => {
setMovies(res);
})
.catch((err) => {
console.log(err);
});
})();
}, []);
예제 ) 더보기 버튼 클릭하면 axios로 가져온 데이터 추가
상품컴포넌트를 map으로 돌려서 state개수만큼 생성했으니까
컴포넌트를 더 불러오는게 아니라 'state에 데이터를 몇개 추가하자!' 라는 코드를 짜야한다.
리액트 환경에서는 'html어떻게 짜지?'가 아니라 데이터를 조작하면 html은 알아서 바뀐다.
let [ 상품, 상품변경 ] = useState(data);
{shoes.map((a, i) => {
return <Shoes 상품={상품[i]} i={i} key={i} />;
})}
버튼을 클릭하면 axios.get으로 데이터를 가져오고
성공했을 때 state를 복사해서 수정하는 코드를 추가한다.
(상품이라는 state에 ajax로 받아온 데이터 추가)
<button className="btn btn-primary" onClick={() => {
axios.get("https://codingapple1.github.io/shop/data22.json")
.then((result) => { 상품변경([...상품, ...result.data]) })
.catch(() => {console.log("fail")});}}>
버튼
</button>
1. 사본생성해서 데이터 추가하는 방법.
2. [...상품, ...result.data]
기존 상품 state를 괄호벗겨서 (...상품) 넣어주고,
result.data라는 데이터도 괄호 벗겨서 , 다음에 넣어준다.
이걸 전부 대괄호 [ ] 로 감싸서 array를 만들어주면 사본생성 안하고 추가가능하다. (object에도 괄호벗기기 연산자 가능하다)
* 로딩중 UI 띄워주고 싶을 때
<button className="btn btn-primary" onClick={() => {
<!-- 로딩중 UI 띄워주는 코드 -->
axios.get("https://codingapple1.github.io/shop/data22.json")
.then((result) => {
<!-- 로딩중이라는 UI 안보이게 처리 -->
상품변경([...상품, ...result.data]) })
.catch(() => {
<!-- 로딩중이라는 UI 안보이게 처리 -->
console.log("fail")});}}>
버튼
</button>
https://yamoo9.github.io/axios/
'Archive' 카테고리의 다른 글
[TIL] Strapi (0) | 2021.11.18 |
---|---|
[JS] this (0) | 2021.11.13 |
[React] useEffect / useReducer (0) | 2021.10.24 |
[React] styled-components / SASS / CSS Module (0) | 2021.10.24 |
[React] Router (0) | 2021.10.24 |