My Develop Log

[노마드코더]실전형 리액트 Hooks 10개 - (useNotification) 본문

React 공부/노마드코더 노트정리

[노마드코더]실전형 리액트 Hooks 10개 - (useNotification)

Developer_Sammy 2023. 2. 14. 20:16
useNotification

useNotification은 Notification API를 활용하여 알림이 실행되는 함수이다.

  • "notification"이라는 title과 함께 body 부분에는 "details notification"으로 작성된 알림이 window 알림에 보여지도록 만든다. (단, granted로 알림이 허가되어 있는 경우시)
// app.js

const useNotification = (title, options) => {
  if (!("Notification" in window)) {
    return;
  }
  
  const fireNotif = () => {
    // default의 경우 모든 알람이 허용되지 x
    if (Notification.permission !== "granted") {
      // promise 부분
      Notification.requestPermission().then((permission) => {
        if (permission === "granted") {
          new Notification(title, options);
        } else {
          return;
        }
      });
    } else {
      new Notification(title, options);
    }
  };
  
  return fireNotif;
};

const App = () => {
  const triggerNotif = useNotification("notification", {
    body: "details notification"
  });
  
  return (
    <div className="APP" style={{ height: "1000vh" }}>
      <h1>useNotification Example</h1>
      <button onClick={triggerNotif}>notification</button>
    </div>
  );
};

export default App;

 

 

만약, 잘 실행이 안된다면 다음과 같이 알림관리에서 크롬의 알림을 받도록 설정이 되어 있는지 확인해야한다.

 

 

더 많은 내용들을 공부하기 위해 Notification api 사이트를 참고해도 좋을 것 같다.

https://developer.mozilla.org/ko/docs/Web/API/notification

 

Notification - Web API | MDN

Notifications API의 Notification 인터페이스는 사용자에게 데스크톱 알림을 설정하고 보여주는데 사용됩니다.

developer.mozilla.org

 

Reference

https://nomadcoders.co/react-hooks-introduction/lectures/1600

 

All Courses – 노마드 코더 Nomad Coders

초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!

nomadcoders.co