오피스아워 (프론트엔드 코치님과 질의응답 및 프젝 코드리뷰) 시간에
진행한 질문과 답변을 기록합니다.
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>
`,
);
});
}
()=>onClickCart()
형식 onClick={(item, _id,) => onClickCart(item, _id)}
document
.querySelector(`#addToCartButton`)
.addEventListener('click', async () => {
localStorage.setItem('cartList', JSON.stringify(item));
console.log('장바구니에 담겼습니다.');
});
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
});
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를 응답 받은 후의 로직
});
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를 응답 받은 후의 로직
});
외우면 되지 않을까?
프론트엔드는 빠르게 발전한다.
예를 들어 리액트의 redux 라는 상태 관리 라이브러리는 2년전까지 매우 많은 곳에서 사용하고 핫했다. 하지만 지금은 사실상 거의 사라지고 사용하지 않는다고 한다. 대신 recoil, jotai, Zustand 등을 사용한다고 하는데,
이러한 라이브러리 같은 경우에는 왜? 생겼는지에 대해 파악하고 공부하면 좋다.
대개 새로운 기술들은 기존 기술들의 어떠한 단점때문에 보완하기 위해 생겨난다.
무엇이 자주 쓰이다가 발전해서, 보완해서 만들어졌는지 흐름을 꼭 파악하고 공부를 하자.
(fetch 관련 자료는 코치님의 자료를 활용했습니다.)