npx create-next-app react-query-project
// next.js 12버전, react 17 버전 설치
npm install next@12 react@17
npm install axios json-server
npm install react-query
function MyApp({ Component, pageProps }) {
const [queryClient] = useState(() => new QueryClient());
return (
<>
<QueryClientProvider client={queryClient}>
<Component {...pageProps} />
<ReactQueryDevtools initialIsOpen={false} position="bottom-right" />
</QueryClientProvider>
</>
);
}
export default MyApp
Data 설정
- json-server 설정
db.json 파일 생성
{
"posts": [
{
"id": 1,
"title": "게시물1",
"author": "jaehan1",
"description": "동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세 무궁화 삼천리 화려 강산 대한사람 대한으로 길이 보전하세"
},
{
"id": 2,
"title": "게시물2",
"author": "jaehan2",
"description": "남산 위에 저 소나무 철갑을 두른듯 바람서리 불변함은 우리 기상일세 무궁화 삼천리 화려 강산 대한사람 대한으로 길이 보전하세"
},
{
"id": 3,
"title": "게시물3",
"author": "jaehan3",
"description": "가을 하늘 공활한데 높고 구름 없이 밝은 달은 우리 가슴 일편단심일세 무궁화 삼천리 화려 강산 대한사람 대한으로 길이 보전하세"
},
{
"id": 4,
"title": "게시물4",
"author": "jaehan4",
"description": "이 기상과 이 마음으로 충성을 다하여 괴로우나 즐거우나 나라사랑하세 무궁화 삼천리 화려 강산 대한사람 대한으로 길이 보전하세 접기"
}
]
}
package.json에 server 추가
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"server": "json-server --watch db.json --port 5000"
}
랜더링 화면 (index.js)
const getPosts = async () => {
const { data } = await axios.get("http://localhost:5000/posts");
return data;
};
export default function Home() {
const {
data: posts,
isLoading,
isError,
error,
} = useQuery("posts", getPosts);
if (isError) {
return <div>{error.message}</div>;
}
return (
<>
<div>
{isLoading ? (
<div>Loading...</div>
) : (
posts?.map((post) => (
<Fragment key={post.id}>
<div>id: {post.id}</div>
<div>제목: {post.title}</div>
<div>작성자: {post.author}</div>
<div>내용: {post.description.slice(0, 100)}...</div>
<hr />
</Fragment>
))
)}
</div>
</>
)
}
실행
npm run dev
npm run server
출처
https://devkkiri.com/post/f14703ea-a105-46e2-89e8-26282de36a3a