2022. 11. 12. 20:39
# useNotification의 기능
const useNotification = (title, options) => {
if (!("Notification" in window)) {
return;
}
const fireNotif = () => {
if (Notification.permission !== "granted") {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
new Notification(title, options);
} else {
return;
}
});
} else {
new Notification(title, options);
}
};
return fireNotif;
};
useNotification은 알림기능을 사용할때 쓰는 hook이다.
반환값은 fireNotif를 반환한다.
fireNotif는 운영체제 내에서 알림설정이 허용 되었을때만 실행된다.
useNotification의 첫번째 인자는 알림의 타이틀을 전달받고
두번째 인자는 옵션으로, Notification의 API웹사이트에서 확인해 볼 수 있다.
https://developer.mozilla.org/ko/docs/Web/API/Notification
( 사용예시로는 { body: "적고싶은 내용" } 옵션을 사용할 예정이다. )
# 설명
if (!("Notification" in window)) {
return;
}
웹의 경우에만 알림이 뜨도록 설정한다.
const fireNotif = () => {
if (Notification.permission !== "granted") {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
new Notification(title, options);
} else {
return;
}
});
} else {
new Notification(title, options);
}
};
return fireNotif;
권한이 허용되지 않았을때 권한획득을 요청한다.
Notification.requestPermission().then() 은 권한을 획득하기 위한 구문이다.
이 후 권한이 허용 되었다면 new Notification(title, options)를 통해서 알림을 띄우고
허용하지 않게되면 return하여 브레이크를 건다.
애초에 허용되어있다면 바로 알림을 띄운다.
# 사용예시
const triggerNotif = useNotification("Can I steal your kimch?", {
body: "I love kimch dont you"
});
<button onClick={triggerNotif}>hello</button>
triggerNotif변수를 선언해서 useNotification을 할당해주고 매게변수에 각각 타이틀과 옵션을 넣어준다.
이 후 버튼요소에 onClick이벤트를 넣어주고 triggerNotif를 할당해주어서 클릭시 Notification기능을 실행시킨다.
'Frontend > React-Hooks' 카테고리의 다른 글
[ React Hook ] 10. useAxios (0) | 2022.11.16 |
---|---|
[ React Hook ] 8. useFullscreen (0) | 2022.11.09 |
[ React Hook ] 7. useFadeIn (0) | 2022.11.05 |
[ React Hook ] 6. useScroll (0) | 2022.11.04 |
[ React Hook ] 5. useNetwork (0) | 2022.11.03 |