Fetch대신 Axios

송나은·2021년 7월 18일
0

React

목록 보기
9/9

how-to-use-axios-with-react

Why use Axios in React?

  • json.stringify() 하지 않아도 된다.
  • 모든 HTTP method와 일치하는 함수명이 존재한다.
  • 상태코드를 확인하고 에러를 처리해야 하는 fetch와 달리 400~500 범위에서 에러를 던진다.
  • 클라이언트 뿐만 아니라 서버에서도 사용할 수 있다.

How to use Axios with React?

npm i axios

const baseURL: "https://songbetter.tommy.com/"

// GET
axios.get(baseURL).then(response => console.log(response.data))

// POST (= PUT과 동일한 방법)
axios.post(`${baseURI}/1`, {/*body*/}, {headers:{/**/}).then(response => console.log(response.data)

// DELETE
axios.delete(`${baseURI}/1`).then(() => alert("POST DELETED!"))

// Erros Handling
.catch(error => console.log(error))

How to create an Axios Instance

const client = axios.create({
  baseURL: "https://songbetter.tommy.com/"
});

client.get("/1").then(response => console.log(response.data))

How to use the Async-Await Syntax with Axios?

useEffect(() => {
  async function getPosts() {
  	const response = await client.get("/1");
  	console.log(response.data);
	}
  getPosts();
}, []);

async function deletePost() {
  await client.delete("/1");
  alert("POST DELETED!")
}

useAxios Custom Hook

npm i use-axios-client

const { data, error, loading } = useAxios({
  url:  "https://songbetter.tommy.com/1"
});
profile
그때그때 공부한 내용과 생각을 기록하는 블로그입니다.

0개의 댓글