yarn add axios
1) Axios get
// url에는 서버의 url이 들어가고, config에는 기타 여러가지 설정을 추가할 수 있다.
// config는 axios 공식문서에서 확인하자.
axios.get(url[, config]) // GET
// src/App.js
import React, { useEffect, useState } from "react";
import axios from "axios"; // axios import 한다.
const App = () => {
const [todos, setTodos] = useState(null);
// axios를 통해서 get 요청을 하는 함수를 생성한다.
// 비동기처리를 해야하므로 async/await 구문을 통해서 처리한다.
const fetchTodos = async () => {
const { data } = await axios.get("http://localhost:3001/todos");
setTodos(data); // 서버로부터 fetching한 데이터를 useState의 state로 set 한다.
};
// 생성한 함수를 컴포넌트가 mount 됐을 떄 실행하기 위해 useEffect를 사용한다.
useEffect(() => {
// effect 구문에 생성한 함수를 넣어 실행한다.
fetchTodos();
}, []);
return <div>App</div>;
};
export default App;
axios.post(url[, data[, config]]) // POST
const onSubmitHandler = async () => {
axios.post('http://localhost:4000/todos', inputValue);
fetchTodos(); //2번의 fetchTodo를 통해 추가 된 데이터를 다시 받아와서 화면에 렌더링 시켜준다.
};
axios.delete(url[, config]) // DELETE
const onDeleteButtonHandler = async (id) => {
axios.delete(`http://localhost:4000/todos/${id}`);
setTodos(
todos.filter((item) => {
return item.id !== id;
})
);
};```
### 5. PATCH
- 보통 어떤 데이터를 수정하고자 서버에 요청을 보낼 때 사용하는 매서드다.
- http 환경에서 서로가 한 약속이자 문맥이기 때문에, 수정을 하고자 반드시 patch, put을 써야만 하는 것은 아니다.
- BE에 의해서 POST를 통해서 "수정"이라는 기능은 충분히 만들 수 있기 때문이다.
```jsx
axios.patch(url[, data[, config]]) // PATCH
const onUdateButtonClickHandler = async () => {axios.patch(`http://localhost:4000/todos/${targetId}`,
{title: desc,});
setTodos(
todos.map((item) => {
if (item.id == targetId) {
return { ...item, title: desc };
} else {
return item;
}
})
);
};
Fetch는 ES6부터 도입된 Javascript 내장 라이브러리다.
Promise 기반 비동기 통신 라이브러리다. axios처럼 데이터를 다루기 쉽고, 내장 라이브러리이기 때문에 별도의 설치 및 import를 필요로 하지 않다.
하지만 fetch가 가진 단점 때문에 Axios를 쓴다.