[SW3] 1109 오피스아워 (onclick 이벤트, fetch)

Bomin·2022년 11월 14일
0

[ALICE SW3]

목록 보기
4/4
post-thumbnail

오피스아워

오피스아워 (프론트엔드 코치님과 질의응답 및 프젝 코드리뷰) 시간에
진행한 질문과 답변을 기록합니다.

1. 화면 페이지 로딩 시 onclick 동작

Q. 페이지 로드 시 버튼 이벤트가 실행되어버리고 버튼 클릭 시 동작하지 않습니다.

const onClickCart = (item, idx) => {
  localStorage.setItem('cartList', JSON.stringify(item));
  //   alert('장바구니에 담겼습니다.');
  console.log('장바구니에 담겼습니다.');
};

async function insertTest() {
  console.log('장바구니상품 test');
  const test = await getData();
  console.log('테스트', test.product);
  test?.product.map((item) => {
    const { _id, title, price, thumbnail } = item;
    // console.log(_id, title, price, thumbnail);
    productTest.insertAdjacentHTML(
      'beforeend',
      `
      <div class="box product-item ">
        <div>
          <figure>
            <img id="productImage" src="${thumbnail}" alt="clothes-image" />
          </figure>
        </div>
        <div class="description">
          <div class="detail">
            <h5 id="productTitle">${title}</h5>
            
          </div>
          <div class="price">
            <h5 id="productPrice">${addCommas(price)}원</h5>
          </div>
          
          <button type="button" class="button is-warning" onClick=${onClickCart(
            item,
            _id,
          )} id="addToCartButton">
          장바구니 추가하기
        </button>
        </div>
      </div>
    `,
    );
  });
}

  • onclick에 함수를 넣으면 안되고 함수 선언을 넣어주어야한다.
  • ()=>onClickCart() 형식
  • onClick={(item, _id,) => onClickCart(item, _id)}
    으로 넣어주었는데도 동작하지않음.

-> 위에 보면 insertAdjacentHTML 이걸로 데이터, 즉 스트링을 넣고 있다. 그래서 이벤트는 addEventListner 로 넣어주어야한다.

  • selectAll('버튼') 으로 찾아서 넣어주면 될 것 같다. (나중에 해보기)
  • insertTest() 안에 아래처럼 작성해서 해결해주었다.
document
  .querySelector(`#addToCartButton`)
  .addEventListener('click', async () => {
   localStorage.setItem('cartList', JSON.stringify(item));
  console.log('장바구니에 담겼습니다.');
});

fetch 에 대해서

fetch 는 뭔가요?

  • 별도 설치가 필요없는 api 호출 도구
  • HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공

원래 fetch를 많이 사용했나요?

  • 아니요! 과거에는 axios를 사용했습니다.

axios 는 어떻게 사용했나요?

axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // a
	})
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

왜 지금은 fetch 를 쓰나요?

  • axios는 별도로 import를 해줘야 하지만, fetch는 브라우저 빌트인이라 그냥 쓰면 된다. -> 브라우저단에서 최신 지원
  • 이로 인해 빌드 용량이 줄어든다. -> axios가 많이쓰일수록 fetch가 유리

fetch는 어떻게 쓰나요?

Get

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => console.log(data));

Post

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "Test",
    body: "I am testing!",
    userId: 1,
  }),
}).then((response) => console.log(response));

Delete

fetch("https://jsonplaceholder.typicode.com/posts/1", {
  method: "DELETE",
})
  .then((response) => response.json())
  .then((data) => console.log(data));

한줄한줄 살펴 보기

fetch('api 주소')
  .then(res => res.json())
  .then(res => {
    // data를 응답 받은 후의 로직
  });

각각의 단계가 무엇을 뜻하는지 명확히 알아야 합니다.

같은 방법으로 바꿔보면?

fetch('api 주소')
  .then(function(res) {
    return res.json();
  })
  .then(function(res) {
    // data를 응답 받은 후의 로직
  });

이해가 안된다면?

  • ES5의 함수 선언식

아래의 코드에서 res 는?

fetch('api 주소')
  .then(function(res) {
    return res.json();
  })
  .then(function(res) {
    // data를 응답 받은 후의 로직
  });

같은 값일까요?
-> 같은 값이 아니다!

이해가 안된다면?

  • 렉시컬 스코프
fetch('api 주소')
  .then(function(res) {

    return res.json();
  })
  .then(function(res) {
    // data를 응답 받은 후의 로직
  });

첫 번째 then 함수에 전달된 인자 res는 http 통신 요청과 응답에서 응답의 정보를 담고 있는 객체입니다. Response Object 라고 합니다.

백앤드에서 넘겨주는 응답 body, 즉 실제 데이터는 보이지 않을 것입니다.

즉 { success: true } 라는 JSON 데이터는 위의 코드로는 console에 찍히지 않을 것이라는 말입니다.

응답으로 받는 JSON 데이터를 사용하기 위해서는 Response Object 의 json 함수를 호출하고, return 해야합니다. 그러면 두 번째 then 함수에서 응답 body의 데이터를 받을 수 있습니다.

그러면 그냥

fetch('api 주소')
  .then(res => res.json())
  .then(res => {
		///
    // data를 응답 받은 후의 로직
  });

외우면 되지 않을까?

앞으로 뭘 더 공부하면 좋을까요?

  • Promise

P.S

프론트엔드는 빠르게 발전한다.
예를 들어 리액트의 redux 라는 상태 관리 라이브러리는 2년전까지 매우 많은 곳에서 사용하고 핫했다. 하지만 지금은 사실상 거의 사라지고 사용하지 않는다고 한다. 대신 recoil, jotai, Zustand 등을 사용한다고 하는데,
이러한 라이브러리 같은 경우에는 왜? 생겼는지에 대해 파악하고 공부하면 좋다.
대개 새로운 기술들은 기존 기술들의 어떠한 단점때문에 보완하기 위해 생겨난다.
무엇이 자주 쓰이다가 발전해서, 보완해서 만들어졌는지 흐름을 꼭 파악하고 공부를 하자.

(fetch 관련 자료는 코치님의 자료를 활용했습니다.)

profile
Frontend-developer

0개의 댓글