Next.js์ API Routes
๋๋ถ๋ถ ํ๋ก์ ํธ ์งํ ์, ๋ฐฑ์๋ API ๊ฐ๋ฐ๋ณด๋ค ํ๋ก ํธ์๋ ๊ฐ๋ฐ์ด ๋ ๋นจ๋ฆฌ ๋๋ ๊ฒฝ์ฐ๊ฐ ๋ง๋ค.
API ๊ฐ๋ฐ ์๋ฃ ์ ํ ์คํธํ ์ ์๋ mockAPI๊ฐ ํ์ํ๋ค.
Next.js์ API Routes ๊ธฐ๋ฅ์ ์ด์ฉํด ๊ฐ๋จํ mockAPI๋ฅผ ๊ตฌํํ ์ ์๋ค.
pages/api ํด๋ ๋ด๋ถ์ ์๋ ํ์ผ๋ค์ ๋ชจ๋ /api/* ๋ก ์์ฒญํ ์ ์๋ค.
// api/reviews/[reviewId]
import { NextApiRequest, NextApiResponse } from "next";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "GET") {
const { reviewId } = req.query;
const review = reviewListMockData.find(({ id }) => +reviewId === id);
res.status(200).json(review);
}
}
React-Query ์ค์
ํ๋ก์ ํธ์์ react-query๋ฅผ ์ฌ์ฉํ ๊ฒ์ด๊ธฐ ๋๋ฌธ์ mockAPI๋ react-query๋ก ์์ฑํ์๋ค.
_app.tsx์์ react-query ๊ด๋ จ ์ค์ ์ ํด์ค๋ค.
import type { AppProps } from "next/app";
import {
QueryClient,
QueryClientProvider,
Hydrate,
} from "@tanstack/react-query";
export default function App({ Component, pageProps }: AppProps) {
const [queryClient] = new QueryClient({
defaultOptions: { queries: { suspense: true } },
});
return (
<QueryClientProvider client={queryClient}>
<Hydrate state={pageProps.dehydratedState}>
<Component {...pageProps} />;
</Hydrate>
</QueryClientProvider>
);
}
_app.tsx์์ ์์ ๊ฐ์ด ์ค์ ํ ๊ฒฝ์ฐ, ๋ฌดํ request ์์ฒญ์ด ๋ฐ์ํ๋ค.
Next.js๋ URL์ด ๋ณ๊ฒฝ๋ ๋๋ง๋ค App ์ปดํฌ๋ํธ๋ฅผ ์ฌ๋ ๋๋งํ๋ค. App ์ปดํฌ๋ํธ๊ฐ ์ฌ๋ ๋๋ง๋ ๋๋ง๋ค ๋ด๋ถ์ ์๋ new QueryClient๊ฐ ๊ณ์ ์ฌ์์ฑ๋๊ธฐ ๋๋ฌธ์ ๋ฌดํ request ์์ฒญ์ด ๋ฐ์ํ๋ค.
Next.js SSR์ ์ฌ์ฉํ๊ณ ์๊ธฐ ๋๋ฌธ์ App ์ปดํฌ๋ํธ ์ธ๋ถ์์ client๋ฅผ ์์ฑํ ์ ์๋ค.
๋ฐ๋ผ์ useState๋ฅผ ์ฌ์ฉํ์ฌ ํด๊ฒฐํ ์ ์๋ค.
์ด๋ ๊ฒ ํ๋ฉด ๋ค๋ฅธ ์ฌ์ฉ์์ ์์ฒญ ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ๊ณต์ ํ์ง ์๊ณ , QueryClient๊ฐ ๋ฑ ํ๋ฒ๋ง ๋ง๋ค์ด์ง๋ค.
import { useState } from "react";
export default function App({ Component, pageProps }: AppProps) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: { queries: { suspense: true } },
})
);
return (
<QueryClientProvider client={queryClient}>
<Hydrate state={pageProps.dehydratedState}>
<Component {...pageProps} />;
</Hydrate>
</QueryClientProvider>
);
}
๊ด๋ จ ๋ด์ฉ์ react query ๊ณต์ ๋ฌธ์์๋ ๋์์๋ค
https://tanstack.com/query/v4/docs/react/guides/ssr#using-hydration
SSR | TanStack Query Docs
React Query supports two ways of prefetching data on the server and passing that to the queryClient. Prefetch the data yourself and pass it in as initialData
tanstack.com
React Query๋ Next.js์ ์๋ฒ์์ ์ฌ๋ฌ ์ฟผ๋ฆฌ๋ฅผ ๋ฏธ๋ฆฌ ๊ฐ์ ธ์จ ๋ค์ ํด๋น ์ฟผ๋ฆฌ๋ฅผ queryClient๋ก dehydrateํ๋ ๊ฒ์ ์ง์ํ๋ค.
์๋ฒ๊ฐ ํ์ด์ง ๋ก๋ ์, ์ฆ์ ์ฌ์ฉํ ์ ์๋ ๋งํฌ์ ์ ๋จผ์ ๋ ๋๋งํ๊ณ JS๋ฅผ ์ฌ์ฉํ ์ ์๋ ์ฆ์ React Query๊ฐ ํด๋น ์ฟผ๋ฆฌ๋ฅผ ์ ๋ฐ์ดํธ ํ๊ฑฐ๋ hydrateํ ์ ์๋ค.
'๐ฉโ๐ค ํ๋ก ํธ์๋ > nextjs' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Nextjs] Linking & Navigating (0) | 2023.01.31 |
---|---|
[NextJS] Pages, Layouts (0) | 2023.01.31 |
[NextJS] Routing (0) | 2023.01.31 |