[React] ZARANARAπŸ‘ΆπŸ» ν”„λ‘œμ νŠΈ (1) λ””ν…ŒμΌ νŽ˜μ΄μ§€ μž₯λ°”κ΅¬λ‹ˆ 톡신

μ–‘μ£Όμ˜Β·2021λ…„ 12μ›” 8일
2

ZARANARA project

λͺ©λ‘ 보기
1/4

λ””ν…ŒμΌ νŽ˜μ΄μ§€μ—μ„œ μž₯λ°”κ΅¬λ‹ˆ λ‹΄κΈ° λ²„νŠΌμ„ λˆ„λ₯΄λ©΄ λ°±μ—”λ“œμ— 데이터λ₯Ό λ³΄λ‚΄μ£ΌλŠ” ν•¨μˆ˜λ₯Ό 생성해보렀 ν•œλ‹€. λ°±μ—”λ“œμ— 보내야 ν•  λ°μ΄ν„°λŠ” μƒν’ˆ id와 μˆ˜λŸ‰μ΄λ‹€. κ°€κ²©μ΄λ‚˜ μƒν’ˆ κ΄€λ ¨ μ •λ³΄λŠ” product_id만 λ³΄λ‚΄μ€˜λ„ λ‹€ μ²˜λ¦¬κ°€ κ°€λŠ₯ν•˜κ²Œλ” ν–ˆλ‹€.

이전에 μž‘μ„±ν•œ μ½”λ“œ >

const handleAddItemToCart = () => {
    fetch(`${API.USER}/cart`, {
      method: 'POST',
      body: JSON.stringify({
        product_id: detailContents.id,
        quantity: productAmount,
      }),
    })
      .then(response => response.json())
      .then(result => {
        if (result.MESSAGE === 'SUCCESS') {
          alert('μž₯λ°”κ΅¬λ‹ˆμ— λ‹΄κ²ΌμŠ΅λ‹ˆλ‹€.');
          window.location.reload();
      });
  };

μˆ˜μ •ν•œ μ½”λ“œ >

const handleAddItemToCart = () => {
    fetch(`${API.USER}/cart`, {
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token'),
      },
      body: JSON.stringify({
        product_id: detailContents.id,
        quantity: productAmount,
      }),
    })
      .then(response => response.json())
      .then(result => {
        if (result.MESSAGE === 'SUCCESS') {
          alert('μž₯λ°”κ΅¬λ‹ˆμ— λ‹΄κ²ΌμŠ΅λ‹ˆλ‹€.');
          window.location.reload();
        } else if (result.MESSAGE === 'ITEM_ALREADY_EXIST')
          alert('이미 μž₯λ°”κ΅¬λ‹ˆμ— μžˆλŠ” μƒν’ˆμž…λ‹ˆλ‹€.');
        else if (result.ERROR === 'INVALID_TOKEN')
          alert('둜그인 ν›„ μž₯λ°”κ΅¬λ‹ˆμ— λ‹΄μ•„μ£Όμ„Έμš”.');
      });
  };

headers에 토큰을 μ‹€μ–΄μ£Όκ³ , body에 μš°λ¦¬κ°€ 데이터λ₯Ό 보내쀄 product_id와 quantityλ₯Ό λ‹΄μ•„μ€€λ‹€. 이후에, 응닡을 λ°›κ³  그에 λŒ€ν•œ 각각의 λ©”μ‹œμ§€λ₯Ό λ„£μ–΄μ€€λ‹€. μˆ˜μ •ν•œ μ½”λ“œμ—μ„œ λˆˆμ—¬κ²¨ λ³Ό 뢀뢄은 headers이닀. λ‘œκ·ΈμΈμ„ ν•œ μœ μ €λ“€λ§Œ μž₯λ°”κ΅¬λ‹ˆμ— μƒν’ˆμ„ 담을 수 μžˆλ„λ‘ ν–ˆλŠ”λ°, 그러렀면 headers에 토큰이 μžˆμ–΄μ•Ό κ°€λŠ₯ν•˜λ‹€. μˆ˜μ • μ „μ—λŠ” 이 뢀뢄을 κ°„κ³Όν•˜κ³  λ„˜μ–΄κ°”μ—ˆλ‹€.


<Button
   handleClick={handleAddItemToCart}
   format="bigger"
   type="button"
   title={`μž₯λ°”κ΅¬λ‹ˆμ— λ‹΄κΈ° (${Number(
   productAmount * price?.split('.')[0]
   ).toLocaleString()} 원)`}
/>

μœ„μ— μž‘μ„±ν–ˆλ˜handleAddItemToCartν•¨μˆ˜λ₯Ό μž₯λ°”κ΅¬λ‹ˆ λ‹΄κΈ° λ²„νŠΌμ— μΆ”κ°€ν•΄μ£Όλ©΄ λœλ‹€.

profile
λšœλ²…λšœλ²…

0개의 λŒ“κΈ€