TIL72.react hook + axios 사용하기

조연정·2021년 1월 28일
0
post-thumbnail

http통신을 위한 API로 기존의 사용해오던 fetch 대신 'axios'를 리액트에 사용해보자.

Axios

Promise를 사용하는 http비동기 통신 모듈로, 자바스크립트 라이브러리이다.

  • 패키지 설치가 필요하고, npm i axios -g
    필요한 곳에 import하여 모듈을 불러와야한다. import axios from 'axios'
  • fetch과 달리, axios는 json을 자동으로 변환해주기 때문에 json화 코드가 불필요하다.

axios에 비동기 처리하기

앞에서 말했듯이 axios는 비동기 방식으로 HTTP데이터 요청을 하기 때문에 비동기 처리과정이 필요할 때가 있다.

async await 사용

useEffect(async() => {
        const result = await axios.get(QUESTIONAPI)
		.then((res) => {
			setQuestions(result.data);
		})
  		.catch((error) => {
        	console.log(error);
        });
	}, []); 

Warning: An effect function must not return anything besides a function, which is used for clean-up.
useEffect함수는 다른 함수를 반환하면 안된다. effect함수 안에 async 함수를 작성하고 즉시 호출해줘야한다.

    useEffect(() => {
	async function fetchData() {
		const result = await axios.get(`${QUESTIONAPI}`);
		setQuestions(result.data.questions);
		console.log(questions);
	}
    fetchData();
}, []);  
profile
Lv.1🌷

0개의 댓글