본문 바로가기

Programming/React

[REACT] useEffect 에서 axios 사용 (async 에러 발생)

문제 : uesEffect 에서 async로 axios 사용 시 error 발생

 

아래와 같이 useEffect에 asycn로 사용 시 에러 발생

useEffect(async(e) =>{
		const result = await axios.get('https://url.url');
		console.log(result.data);
		}
},[]);

Warning:

An effect function must not return anything besides a function, which is used for clean-up.

It looks like you wrote useEffect(async () => ...) or returned a Promise.

Instead, write the async function inside your effect and call it immediately:

useEffect(() => {
   async function fetchData() { // You can await here
   const response = await MyAPI.getData(someId);
   // ...
   } fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

effect함수는 다른 함수를 반환해선 안된다고 한다.

 

이 경우엔, 위 warning 설명과 같이 fetchData()로 async 로 사용 가능

useEffect( (e) => {
		async function fetchData(){
        	const result = await axios.get('https://url.url');
            console.log(result.data);
        }
		fetchData();
},[]);

 

 

반응형