본문 바로가기
D.evelop/React

[02] JSON server로 Mock data서버 실행하여 React Query로 호출

by Danne 2024. 1. 17.

JSON server 로 Mock data서버 실행하여 React Query로 호출하기 - 02

 

[01] JSON server 세팅

1. Mock 데이터 파일 생성

2. json-server 설치

3. 실행 script 추가

4. 서버 실행

 

[02] React Query를 사용하여 데이터 호출

5. axios 설치

6. React Query 설치

7. <QueryClientProvider> 추가

8.  데이터 호출


* 굳이 React Query로 호출 할 필요가 없으나, 라이브러리 세팅이 잘 되었는지 확인 겸.
겸사겸사 React Query로 데이터를 GET 해보았습니다.


[02] React Query를 사용하여 데이터 호출

 

5. axios 설치

npm i axios

 

https://www.npmjs.com/package/axios

 

axios

Promise based HTTP client for the browser and node.js. Latest version: 1.6.5, last published: 11 days ago. Start using axios in your project by running `npm i axios`. There are 115583 other projects in the npm registry using axios.

www.npmjs.com

 

 

6. React Query 설치

npm i @tanstack/react-query @tanstack/react-query-devtools

 

https://tanstack.com/query/latest/docs/react/installation

 

Installation | TanStack Query Docs

React Query is compatible with React v18+ and works with ReactDOM and React Native. If you're not using a module bundler or package manager, you can also use this library via an ESM-compatible CDN such as ESM.sh. Simply add a tag to the bottom of your HTML

tanstack.com

 

 

7. <QueryClientProvider> 추가

 

QueryClientProvider로App을 감싼다.

// index.tsx

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import ModalProvider from './context/ModalProvider';
const queryClient = new QueryClient();

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement,
);

root.render(
  <React.StrictMode>
    <BrowserRouter>
      <QueryClientProvider client={queryClient}>
          <App />
        </ModalProvider>
        <ReactQueryDevtools initialIsOpen /> <!--필수 아님-->
      </QueryClientProvider>
    </BrowserRouter>
  </React.StrictMode>,
);

 

 

8.  useQuery 를 사용해 데이터 호출

// Post.tsx

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useQuery } from '@tanstack/react-query';

const useGetMemo = () => {
  return useQuery({
    queryKey: ['memo'],
    queryFn: async () => {
      const { data } = await axios.get('http://localhost:3001/memo');
      return data.result;
    },
  });
};

export const Post = () => {
  const { data } = useGetMemo();

  const [memoList, setMemoList] = useState([
    {
      "id": 0,
      "title": "",
      "body": ""
    }
  ]);

  useEffect(() => {
    data && setMemoList(data);
  }, [data]);

  return (
        <ul>
          {memoList.length > 0 &&
            memoList.map((item: any, i: number) => {
              return (
                <li key={i}>
                  <p>{item.id}</p>
                  <p>{item.title}</p>
                  <p>{item.body}</p>
                </li>
              );
            })}
        </ul>
    );
};

export default Post;

 

 

 

반응형

댓글