새소식

React ·JS·TS

(React Hooks) useEffect - useNotification / useAxios

  • -

useNotification

 

https://developer.mozilla.org/en-US/docs/Web/API/Notification

 

 

Notification - Web APIs | MDN

The Notification interface of the Notifications API is used to configure and display desktop notifications to the user.

developer.mozilla.org

 

notification API 를 활용한  알람이 실행되는 함수

 

  if(!("Notification" in window)){
    return;
  }

window가 아니라면 브라우저에서 notificatio을 지원하지 않기때문에 예외처리 해준다.

 

 

 

 

const fireNotif = () => {
    if(Notification.permission !== "granted"){
      Notification.requestPermission().then(permission => {
        if(permission === "granted"){
          new Notification(title, options);
        }else {
          return;
        }
      })
    }else {
      new Notification(title, options);
    }
  };

알람을 생성하는 함수로 fireNotif() 를 선언 해준다.

Notification.permission에서 가능한 값은

.then(permission)에서 permission의 값으로 들어가는 default / denied / granted 중 하나로 들어간다.

default  >> 사용자의 선택을 알 수 없기 때문에 브라우저가 거절한 상태의 값으로 작동하게됨

denied  >> 사용자가 알림 표시를 거절

granted  >> 사용자가 알림 표시를 허용

fireNotif return

 

 

 

 

  const triggerNotif = useNotification("Can I steal?", {body : "I love it!"})

위와같이 title과 options를 작성해서 onclick 이벤트에 담아준다.

options 값으로 { body : "   " }  사용

 

 

위와같이 알람이 생성되어 출력된다.

 

 

 

 

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;
}
 
export default function App() {
  const triggerNotif = useNotification("Can I steal?", {body : "I love it!"})
  return (
    <div className="App" style={{height : "1000vh"}}>
      <button onClick={triggerNotif}>Hello</button>
    </div>
  );
}

useNotification 전체코드

 

 

 

 

 

useAxios

import defaultAxios from "axios";

useAxios.js 파일을 새롭게 만들어 작성한다

axios >> HTTPrequest 만드는것

 

const useAxios = (options, axiosInstance = defaultAxios) => {
    if(!options.url) {
        return;
    }
}

default값으로 axiosClient를 요청

axiosInstance값을 받지 못하면 import한 패키지에서 axios를 얻어서 전달

options = object

options으로 url을 받지못하면 return 시킨다.

 

 

axios는 약간의 customization과 configuration을 허용해준다.

Ex) default URL 설정,  auto header 설정, 등.. 

 

 

cd my-app  >> 패키지 경로를 통해서 경로설정

npm install axios >>  axios패키지 설치

 

 

import defaultAxios from "axios";

const useAxios = (options, axiosInstance = defaultAxios) => {
    if(!options.url) {
        return;
    }
};

export default useAxios;

원래 작업하던 js파일에서 함수호출을 하기위해서 useAxios로 export default 해준다.

 

 

 

import useAxios from "./useAxios";

useAxios.js로 만들었던 파일을 import 한다 (export한 함수 호출시 자동으로 import)

 

 

export default function App() {
  const request = useAxios({url : "https://yts.mx/api/v2/list_movies.json"})
  return (
    <div className="App" style={{height : "1000vh"}}>
      <h1>hello</h1>
    </div>
  );
}

useAxios는 options로 url을 받고 instance는 기본값이 설정되어 있으므로 작성하지 않았음.

 

 

 

 

const useAxios = (options, axiosInstance = defaultAxios) => {
    const [state, setState] = useState({
        loading : true,
        error : null,
        data : null
    })
    useEffect(() => {
        if(!options.url) {
            return;
        }
        axiosInstance(options).then(data => {
            setState({
                ...state,
                loading : false,
                data
            }).catch(error => {
                setState({...state, loading:false, error})
            });
        });
    }, []);
    return state;
};

useEffect로 axios 호출, 업데이트를 하지 않기위해 [ ] 달아주기

axios는 데이터를 받으면 .then / error가 있다면  .catch를 사용해서 잡아주기.

 

 

 

 

    useEffect(() => {
        if(!options.url) {
            return;
        }
        axiosInstance(options).then(data => {
            setState({
                ...state,
                loading : false,
                data
            });
        }).catch(error => {
            setState({...state, loading:false, error})
        });
    }, [trringer]);
    return {...state, refetch};

refetching(다시가져오기)하는 방법

>> dependency에 trringer를 넣고 리턴값을 변경

trringer가 변경되면 useEffect() 는 다시 실행된다.

 

 

 

 
    const [trringer, setTrigger] = useState(0);
    const refetch = () => {
        setState({
            ...state,
            loading : true
        });
        setTrigger(Date.now());
    }

refetch 함수는 새로운 데이터를 다시 가져오기 위해 

...state로 기존 상태의 내용을 refetch 함수 에 복사하고

loading 상태를 true로 설정하고 trigger 값을 Date.now()로 설정하여 호출될 때마다 요청이 다시 시작된다.

 

 

 

 

 

export default function App() {
  const {loading, data, error, refetch} = useAxios({
  });
  console.log(`Loading : ${loading}\nError : ${error}\nData : ${data}`);
  return (
    <div className="App" style={{height : "1000vh"}}>
      <h1>{data && data.status}</h1>
      <h2>{loading && "Loading"}</h2>
      <button onClick={refetch}>refetch</button>
    </div>
  );
}

App.js 전체코드

 

 

 

 

import defaultAxios from "axios";
import { useEffect, useState } from "react";

const useAxios = (options, axiosInstance = defaultAxios) => {
    const [state, setState] = useState({
        loading : true,
        error : null,
        data : null
    });
    const [trringer, setTrigger] = useState(0);
    const refetch = () => {
        setState({
            ...state,
            loading : true
        });
        setTrigger(Date.now());
    }
    useEffect(() => {
        if(!options.url) {
            return;
        }
        axiosInstance(options).then(data => {
            setState({
                ...state,
                loading : false,
                data
            });
        }).catch(error => {
            setState({...state, loading:false, error})
        });
    }, [trringer]);
    return {...state, refetch};
};

export default useAxios;

useAxios.js 전체코드

 

 

 

Contents

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

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