http통신을 위한 API로 기존의 사용해오던 fetch 대신 'axios'를 리액트에 사용해보자.
Promise를 사용하는 http비동기 통신 모듈로, 자바스크립트 라이브러리이다.
npm i axios -g
import axios from 'axios'
앞에서 말했듯이 axios는 비동기 방식으로 HTTP데이터 요청을 하기 때문에 비동기 처리과정이 필요할 때가 있다.
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();
}, []);