서버와 통신해서 데이터를 가져오고 상태에 따라 화면에 렌더링되는 훅 생성
import { useEffect, useState } from 'react';
// 컴포넌트 간 로직(logic) 공유
// 사용자 정의 훅(함수)을 작성
export default function useFetchData(endpoint) {
// 훅의 규칙 (컴포넌트 또는 다른 훅 내부에서만 사용 가능)
// custom hook 내부에서 built-in hook 사용 가능
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
setIsLoading(true);
async function fetchProducts() {
try {
const response = await fetch(endpoint, {
signal: controller.signal,
});
const responseData = await response.json();
setData(responseData);
} catch (error) {
if (!(error instanceof DOMException)) {
setError(error);
}
} finally {
setIsLoading(false);
}
}
fetchProducts();
// StrictMode(x2, detect impure function component)
// mount(1, 요청 1) → unmount (취소 1) → mount(2, 요청 1) -> 응답 1
return () => {
controller.abort();
}
}, [endpoint]);
return { data, isLoading, error };
}
// 사용법
// const { data, isLoading, error } = useFetchData(PB_PRODUCTS_ENDPOINT);
AbortController 인터페이스는 하나 이상의 웹 요청을 취소할 수 있게 해준다.
AbortController와 그것의 signal은 웹 플랫폼에서 제공하는 기능으로, 네트워크 요청이나 다른 비동기 작업을 취소하고 관리하는 데 사용됩니다.
주로 HTTP 요청을 취소하거나 중단하는 데 활용되는데, 이를 통해 요청이 완료되기 전에 불필요한 네트워크 트래픽을 줄이고 불필요한 리소스를 아낄 수 있습니다.
AbortController 메서드와 속성을 제공
abort()
: AbortController의 signal을 사용하여 연결된 비동기 작업을 취소하고 중단
signal
: AbortController의 인스턴스에 연결된 AbortSignal 객체입니다. signal은 비동기 작업을 취소하거나 감지하는 데 사용
AbortSignal 속성
aborted
: 이벤트 종류(Event type)로서 true인 경우 해당 비동기 작업이 취소되었음을 나타냅니다.라우터 설치
pnpm add react-router-dom
const router = createBrowserRouter([
// Router Object
// 경로(path), 요소(element ← <Component />)
{ path: '/', element: <Home /> },
{ path: '/products', element: <Products /> },
{ path: '/contact', element: <Contact /> },
]);
console.log(router);
function App() {
return (
<div className="App">
<RouterProvider router={router} />
</div>
);
}
export default App;
라우터 프로바이더 페이지 갈아끼워주는 애
아울렛이 가리키는 것