리액트 useRef를 활용한 custom hook 클릭감지

안녕하세요·2023년 12월 27일
0

react

목록 보기
7/32
post-thumbnail
import { useRef } from 'react';

export default function CartItemDelete({userInfo,cid}) {

  const buttonRef = useRef(null);
  useCartDelete(buttonRef, userInfo,cid);
  

  return(
    <Button 
    variant="danger" 
    type="button" 
    // data-value={cid} 
    // onClick={handleDelete} 
    ref= {buttonRef}>삭제</Button>

  );
  
}

버튼을 누르면 useCartDelete라는 커스텀훅이 실행되어 삭제하는 컴포넌트

import axios from 'axios';
import { useEffect } from 'react';



export default function useCartDelete(buttonRef, userInfo, cid) {

  useEffect(() => {
    const handleDelete = async (e) => {
      let confirmResult = window.confirm('정말로 삭제하시겠습니까?');
      if (confirmResult) {

        axios({
          method: 'delete',
          url: `http://localhost:8000/carts/${userInfo.id}/${cid}`,
        })
          .then(res => {
            alert(JSON.stringify(res.data))
            window.location.reload();
          })
          .catch((err) => { console.log(err) });
      }

    }

    //buttonRef에 클릭 이벤트 추가
    if (buttonRef && buttonRef.current) {
      buttonRef.current.addEventListener('click', handleDelete);
    }
  }, [buttonRef])



}

클릭시 if (buttonRef && buttonRef.current) 조건이 충족되어 handleDelete 이벤트 실행

0개의 댓글