기억의 실마리
2022. 11. 16. 19:59

# useAxios의 기능

기능은 fetch와 유사하고 간단하게 사용할땐 fetch를,

확장성을 염두해봤을 땐 axios를 쓰는게 좋다.

fetch와 다르게 인스턴스를 사용할 수 있는 장점도 있다.

(두번째인자에 넣지 않을경우 기본값으로 설정된다.)

 

import defaultAxios from "axios";
//터미널에 npm i axios 하여 인스톨한 후 임포트해준다.

import { useEffect, useState } from "react";

const useAxios = (opts, axiosInstance = defaultAxios) => {
    //opts 는 api를 등록할 수 있다. fetch와 다르게 바로 json화 되는게 axios의 장점이다.
    //두번째 인자 axiosInstance는 인스턴스이고 아무것도 넣지않으면 기본값으로 적용

    const [state, setState] = useState({
        loading: true,
        error: null,
        data: null
    });
    //로딩, 에러, 데이터를 사용할 것이기 때문에 각각의 key와 value의 디폴트를 설정해준다.
    
    const [trigger, setTrigger] = useState(0);
    if (!opts.url) {  //유효성을 검사한다. 기본적으로 opts(API)는 url이기 때문
        return;
    }
    const refetch = () => {
        setState({
            ...state,
            loading: true
        });
        setTrigger(Date.now());
    };
    /* 리패치를 위한 함수이며 함수 실행시 setTrigger로 인해서 
    함수가 실행될 때마다 trigger는 계속해서 다른 값을 반환한다.
    이 후에 useEffect의 deps로 넣기 위한 트리거다.( 리패치 해야되니까 ) */


    useEffect(() => {
        axiosInstance(opts)       //fetch와 같은 기능을 해주고
            .then((data) => {     //로딩이되면(then) setState를 통해서 state값이 바뀐다.
                setState({
                    ...state,
                    loading: false,
                    data
                });
            })
            .catch((error) => {
                setState({ ...state, loading: false, error });
                //catch 는 에러를 캣치하며, reject상태일경우 내부 메소드를 실행한다.
                });
    }, [trigger]);
    //트리거가 deps에 들어가 있으니 trigger가 바뀌면 re-render한다.
    
    return { ...state, refetch };
    //반환값은 state의 모든 리터럴과 refetch함수이다.
};

 

# 사용예시

const { loading, data, refetch } = useAxios({
    url: "https://yts.mx/api/v2/list_movies.json"
  });

  return (
    <div className="App" style={{ height: "1000vh" }}>
      <h1>{data && data.status}</h1>
      <h2>{loading && "Loading"}</h2>
      <button onClick={refetch}>Refetch</button>
    </div>
  );

useAxios에서 opts를 { url: " 주소 " } 오브젝트로 전달해주었고

data가 있으면(API를 정상적으로 받아오면) data.status가 h1에 마운트되도록 만들었다.

로딩이 true일 경우에만 Loading이라는 문자열을 h2에 마운트하고

Refetch버튼을 누르면 refetch함수를 통해서 새로고침된다.

'Frontend > React-Hooks' 카테고리의 다른 글

[ React Hook ] 9. useNotification  (0) 2022.11.12
[ 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
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