새소식

React ·JS·TS

useConfirm / usePreventLeave

  • -

useConfirm 

const useConfirm = (message = "", onConfirm) => {
  if(!onConfirm || typeof onConfirm !== "function"){
    return;
  }
  const consfirmAction = () => {
    if(window.confirm(message)){
      onConfirm();
    }
  };
  return consfirmAction;
};

message의 default값은 공백으로 설정

confirm function이 브라우저에 message를 가지고 있다면 callback() 호출

 

 

 

 

confirm()  ==>  window.confirm() 사용하여 해결

 

 

 

 

export default function App() {
  const deleteWorld = () => console.log("Delete the world...");
  const confirmDelete = useConfirm("sure?" , deleteWorld);
  return (
    <div className="App">
      <h1>Hi</h1>
      <button onClick={confirmDelete}>Delete the world</button>
    </div>
  );
}

confirmDelete는 return받은 confirmAction값

 

 

위 코드를 실행하면 confirmDelete에 등록된 "sure?"이  alert창을 통해 출력되며 True, False 를 반환받는다

True반환시 등록된 deleteWorld함수를 실행

 

 

 

 

  const abort = () => console.log("Aborted");
  const confirmDelete = useConfirm("sure?" , deleteWorld, abort);

useConfirm인자를 하나 추가 할 경우에

deleteWorld와 abort 두개다 실행이 된다.

 

 

prevent Leave

홈페이지에서 글 작성시에 글이 저장되지 않은 상태일때 사용한다.

 

 

 

 

import React from "react";
const useConfirm = (message = "", onConfirm, onCancel) => {
  if(!onConfirm || typeof onConfirm !== "function"){
    return;
  }
  if(onCancel && typeof onCancel !== "function"){
    return;
  }
  const consfirmAction = () => {
    if(confirm(message)){
      onConfirm();
    }else {
      onCancel();
    }
  };
  return consfirmAction;
};

export default function App() {
  const deleteWorld = () => console.log("Delete the world...");
  const abort = () => console.log("Aborted");
  const confirmDelete = useConfirm("sure?" , deleteWorld, abort);
  return (
    <div className="App">
      <h1>Hi</h1>
      <button onClick={confirmDelete}>Delete the world</button>
    </div>
  );
}

useConfirm 전체코드

 

 

 

 

usePreventLeave

API에 무언가를 보내고 있을 때 사람들이 창을 닫지 않기를 바랄때 보호 할 수 있게 활성화 O

API가 응답을 완료해서 사람들이 창을 닫더라도 상관없을 땐 활성화 X

 

 

 

const usePreventLeave = () => {
  const listener = event => {
    event.preventDefault();
    event.returnValue = "";
  }
  const enablePrevent = () => window.addEventListener("beforeunload", listener)
  const disablePrevent = () => window.removeEventListener("beforeunload", listener)
  return {enablePrevent, disablePrevent};
}

export default function App() {
  const {enablePrevent, disablePrevent} = usePreventLeave();
  return (
    <div className="App">
      <h1>Hi</h1>
      <button onClick={enablePrevent}>Protect</button>
      <button onClick={disablePrevent}>Unprotect</button>
    </div>
  );
}

beforeunload는  returnValue를 요구함

window는 beforeunload라는 이벤트를 갖게 되고 event.preventDefault()를 하게되면

Protect버튼 클릭후 창을 닫을시 window가 사이트를 종료할 것인지 묻는다.

{enablePrevent, disablePrevent}을  return 하여 사용

 

event.returnValue = "" 를 작성해줘야 작동함.

 

Unprotect 버튼을 클릭시 이벤트를 삭제하여 창을 닫을시 사이트 종료여부를 묻지않는다.

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.