import React ,{useState, useEffect} from 'react';
import axios from 'axios';
export default function App(){
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(()=>{
axios("https://randomuser.me/api")
.then((res)=>{
setData(res.data)
})
.catch((err)=>{
console.error("fetch error",err);
setError(err)
})
.finally(()=>{
setLoading(false);
})
},[])
if(error) return "error";
if(loading) return "loading";
return(
<>
<img src={data.results[0].picture.large} alt="large"/>
<pre>
{JSON.stringify(data,null,2)}
</pre>
<a href={data.items[0].selfLink}>법륜스님 책</a>
</>
)
}
3초동안 로딩진행후 json 가져오고 싶을때 하단처럼 변경하면 된다 !
.finally(()=>{
setTimeout(function(){setLoading(false)},3000)
// setLoading(false)
})
},[])
'프론트엔드 공부 > react' 카테고리의 다른 글
useState,useEffect 로 parrallex구현 (0) | 2021.07.14 |
---|---|
chart.js활용하여 chart 만들기 (0) | 2021.07.11 |
npm create-react-app 설치시 몇가지 빈폴더 나오는 경우 (0) | 2021.07.03 |
img 절대경로 설정시 Module not fout:Can't resolve '이미지경로' (0) | 2021.06.10 |
npx create-react-app (0) | 2021.05.29 |