(React) 쇼핑몰 만들기 - get 요청으로 서버에서 데이터 받아오기

고민지·2022년 7월 24일
0

React

목록 보기
18/25
post-thumbnail

서버에서 데이터 받아오는법

  1. xmlHttpRequest
  2. fetch()
  3. axios(외부라이브러리)

3번을 사용하여 진행해보자.

npm install axios
말안해도 알겠쥬?

App.js 파일에 다음과 같은 버튼을 추가한다.

<Routes>
.
.
</Routes>
<button
	onClick={() => {
      axios
      .get("https://codingapple1.github.io/shop/data2.json")
      .then((result) => {
      const data = result.data;
	  const newShoes = [...shoes, ...data];
	  setshoes(newShoes);
  })
    .catch(() => {
    console.log("실패함");
  });
}}
  >
    버튼
</button>

state shoes 도 배열이고, axios로 갖고온 result.data 도 배열이다.
shoes 에 추가하는 방법은 여러가지가 있다.

배열에 배열 데이터를 추가하는 방법

 const data = result.data;
 const newShoes = [...shoes];
 data.map((item, index) => {
   newShoes.push(item);
 });
 setshoes(newShoes);
const data = result.data;
const newShoes = [...shoes];
newShoes.concat(data);
setshoes(newShoes);  
const data = result.data;
const newShoes = [...shoes, ...data];
setshoes(newShoes);  

나는 3번의 방법을 사용했다.

그러나 버튼을 눌러보면 추가한 상품의 사진이 나오지 않는다.
get 요청으로 가져온 데이터에는 src 속성이 없기 때문이다.
사진 src의 shoes1.jpg, shoes2.jps ...을 볼 때 shoes뒤에 숫자만 바뀌면 될 것 같다.
Shoe.js 파일을 다음과 같이 수정해준다.

/* eslint-disable */

function Shoe(props) {
  return (
    <div className="container">
      <div className="row">
        {props.shoes.map((item, index) => {
          const i = index + 1;
          return (
            <div className="col-md-4" key={index}>
              <img
                src={"https://codingapple1.github.io/shop/shoes" + i + ".jpg"}
                width="80%"
              />
              <h4>{item.title}</h4>
              <p>{item.content}</p>
              <p>{item.price}</p>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default Shoe;

변수 i를 만들어 문자열 안에 넣어주었다.
이제 shoes.js 의 데이터에서 src를 모두 지워줘도 될 것이다.

const shoes = [
  {
    id: 0,
    title: "White and Black",
    content: "Born in France",
    price: 120000,
  },

  {
    id: 1,
    title: "Red Knit",
    content: "Born in Seoul",
    price: 110000,
  },

  {
    id: 2,
    title: "Grey Yordan",
    content: "Born in the States",
    price: 130000,
  },
];

export default shoes;

Detail.js 파일에도 이미지 부분을 아래와 같이 수정한다.

 <img src={"https://codingapple1.github.io/shop/shoes"+id+".jpg"} width="100%"/>

ajax 기본개념

  1. axios.get() 을 동시에 여러개를 요청하고 싶으면
    Promise.all([axios.get(), axios.get() ...]).then~
    Promise를 사용해주면 된다.
  2. 기본 자바스크립트 fetch 문법은 다음과 같이 데이터 형식을 변환해줘야 한다.
    fetch().then(re=>re.json()).then(data=>{...})
    axios 는 데이터값을 json으로 자동으로 변환해주기 때문에 더 편리한 것이다.
profile
도전 성취 성장을 향한 개발자

0개의 댓글