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

React : 더보기 버튼 누르면 ajax axios로 상품 더 가져오기

Zoeeey 2023. 5. 31. 13:47

조건

더보기 버튼을 누르면 ajax axios로 링크의 상품 데이터(json형태)를 불러온다.


풀이

처음에는 click state를 만들어서 true/false 스위치로 true 시 나올 상품.../false 시 나올 상품.. 하고 삼항연산자로 넣었는데, 그럴 필요가 전혀 없었다.

function App() {
  let [shoes, setShoes] = useState(data);
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={ <Main shoes={shoes} setShoes={setShoes}/> }/>
      </Routes>
    </div>
  );
}
function Main(props){
  let moreProduct = function(){
    axios.get('https://codingapple1.github.io/shop/data2.json')
      .then((response)=>{
        let newProduct = response.data;
        let copyShoes = [...props.shoes, ...newProduct];
        props.setShoes(copyShoes);
      })
      .catch(()=>{ console.log(`실패자`) })
  }
  return (
    <>
    <div className="main-bg" style={{backgroundImage : 'url('+ mainBg +')'}}></div>
    <div className="container">
      <div className="row">
        {
          props.shoes.map((a, i) => (<Product shoes={props.shoes} i={i} key={i} />))
        }
      </div>
    </div>
    <button className="" onClick={()=> { moreProduct() }}>더보기</button>
    </>
  )
}
  1. axios로 데이터를 get 해온 다음, then에 get메소드에서 반환된 promise의 결과 객체response로 명명했다.
  2. response의 데이터 response.datanewProduct 안에 담았다.
  3. copyShoesprops로 넘겨받은 기존 shoes 데이터와 newProduct를 array로 함께 넣어두었다.
  4. props로 넘겨받은 setShoesshoescopyShoes로 바꿔주었다.

알게 된 점

  • then에 들어가는 promise의 결과 객체response라고 작성하는 게 일반적인 듯 하나, 아예 다르게 작명해도 작동되었다.
  • 그러나 해당 결과의 데이터 (xxx.data)에서 data 다르게 작성했을 때 작동되지 않았다.
  • props로 setShoes같은 state 함수도 넘겨줄 수 있다.

더 수정할 수 있다면

function Product(props){
  return (
    <div className="col-md-4">
      <img src={`${process.env.PUBLIC_URL}/shoes${props.i + 1}.jpg`} width="80%" />
      <h4>{props.shoes[props.i].title}</h4>
      <p>{props.shoes[props.i].price}</p>
    </div>
  )
}

불러오는 product images가 PUBLIC+URL로 되어있어서 이미지를 불러오는 데 오류가 나는 것 같은데 이쪽을 좀더 고민해봐야겠다.


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