axios
axios 설치
yarn add axios
npm i axios
get
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
post
axios.post("url", {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
// response
}).catch(function (error) {
// 오류발생시 실행
})
delete
axios.delete('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
put
axios.put("url", {
username: "",
password: ""
})
.then(function (response) {
// response
}).catch(function (error) {
// 오류발생시 실행
})
동시요청
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) {
// 두개의 요청이 성공했을 때
}));
리액트에서 사용하기
axios를 이용해서 GET으로 컴포넌트 처음 렌더링 하면 fetchAPI 함수 호출
setSate를 통해서 state에 API 요청 데이터를 넣어줘서 사용 가능하다
async function fetchAPI() {
const response = await fetchAPI();
const data = response.data;
setData(data);
}
useEffect(() => {
fetchAPI();
}, []);
onClick하면 axios로 post 요청하기
const onClick = () => {
axios
.post('/api/save', {
data: data,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
};
전체 코드
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function fetchAPI() {
return axios.post('/api/keypad');
}
export default function TestComponent() {
const [data, setData] = useState();
async function fetchAPI() {
const response = await fetchAPI();
const data = response.data;
setData(data);
}
const onClick = () => {
axios
.post('/api/password', {
data: data,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
};
useEffect(() => {
fetchAPI();
}, []);
return (
<>
<div>{data}</div>
<button onClick={onClick}></button>
</>
);
}
공식 사이트
'리액트' 카테고리의 다른 글
리액트 useImperativeHandle, forwardRef로 부모 컴포넌트가 자식 컴포넌트의 메서드나 변수에 직접 접근 (0) | 2024.01.17 |
---|---|
리액트에서 dangerouslySetInnerHTML 렌더링하기 (0) | 2023.10.11 |
리액트에서 string 데이터와 ReactElement가 혼합된 데이터 렌더링 하기 (0) | 2023.10.11 |
FileReader로 파일 읽고 업로드한 파일 미리보기 구현 (0) | 2023.09.18 |
리액트에서 조건부 클래스 이름줄 때 classNames 라이브러리 사용 (0) | 2023.08.27 |
리액트 컴포넌트에서 axios API 요청하기