안녕하새요, 코드리뷰 신청합니다.
fetch API를 이용해서 ‘GET’ 그리고 'POST’를 할 수 있는 custom hooks를 만들어봤습니다.
사용법 :
const { data: fetchData = [], loading: fetchLoading, error: fetchError } = useFetch('/url');
const { data: postData, loading: postLoading, error: postError, post } = useFetch('/url', 'POST');
<DisplayData={fetchData} /// get method
<Button onClick={()=post({id:4, name: 'codeJong'}) /// post method
//useFetch
const useFetch = (url, method) ={
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(false);
    if (!url || url.length === 0) {
        console.error('Missing url');
        if (!error) setError(true);
        if (loading) setLoading(false);
        return { data, loading, error };
    }
    const runFetchProcess = async (data) ={
        const requestMethod = method === 'POST' ? 'POST' : 'GET';
        let requestHeader = {
            headers: {
                'Content-Type': 'application/json',
            },
            method: requestMethod,
        };
        if (data) {
            requestHeader.body = JSON.stringify(data);
        }
        try {
            const response = await fetch(url, requestHeader);
            const responseData = await response?.json();
            if (!response.ok) {
                setLoading(false);
                setError(true);
                throw Error('something wrong here mate');
            } else {
                setData(responseData);
                setLoading(false);
            }
        } catch (e) {
            setError(true);
            console.error('useFetch.js', e);
        } finally {
            setLoading(false);
        }
    };
    const post = (data) ={
        if (!data) return;
        runFetchProcess(data);
    };
    useEffect(() ={
        if (method) return;
        runFetchProcess();
    }, []);
    return { data, loading, error, post };
};
export default useFetch;
좋은 리뷰 기대할깨요 
 감사합니다.
꾸벅
코드종 Youtube 채널 바로가기


