⚛️ React/문제풀기 (코딩애플: React)

React : ajax 상품 불러오기 전 로딩중 만들기

Zoeeey 2023. 5. 31. 15:37

조건

더보기 버튼을 눌렀을 때 ajax로 상품을 불러오는 중에 로딩중 박스를 띄우고, 상품을 불러온 후에는 안보이게 만들기


풀이

get 전로딩중을 불러오고, then 마지막풀어주었다.

function Main(props){
  let [alert, setAlert] = useState(false);
  let moreProduct = function(){
    setAlert(true);
    axios.get('https://codingapple1.github.io/shop/data2.json')
      .then((response)=>{
        let newProduct = response.data;
        let copyShoes = [...props.shoes, ...newProduct];
        props.setShoes(copyShoes);
        setAlert(false);
      })
      .catch(()=>{ console.log(`실패자`) })
  }
  return (
    <>
    <div className="main-bg" style={{backgroundImage : 'url('+ mainBg +')'}}></div>
    <div className="container">
      <div className="row">
        {alert && <Alert />}
        {
          props.shoes.map((a, i) => (<Product shoes={props.shoes} i={i} key={i} />))
        }
      </div>
    </div>
    <button className="" onClick={()=> { moreProduct() }}>더보기</button>
    </>
  )
}
function Alert(){
  return (
    <div className="alert alert-warning">
          상품 로딩중
    </div>
  )
}

출처 : 코딩애플 https://codingapple.com/