Server-Client 연결 및 Front-end CRUD form 작성

하성화·2022년 5월 12일
0

Server-Client 연결

mkdir client
cd client
npx create-react-app .
npm install @apollo/client graphql

client 폴더를 만들고 create-react-app을 통해 react-app 생성 후 Server-Client 연결을 위한 라이브러리 설치

// client/src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";

const client = new ApolloClient({
  uri: "http://localhost:5000/graphql",
  cache: new InMemoryCache(),
});

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);

Server와 연결하기 위해 client를 선언하고 uri에 grahql서버를 등록하고
AplloProvider로 App을 감싸준다.

InMemoryCache란?
apolloclient에서는 gql의 결과를 InMemoryCache에 저장하고, 이를 통해 불필요한 네트워크 요청 없이 동일한 데이터에 대해 요청할 수 있다.

Front-end formUI 작성

간단한 폼UI 작성을 위해 bootstarp을 적용하였다.

<!-- client/public/index.js -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

입력 Form

// client/src/components/AddBook.js
import React from 'react';

const AddBook = () => {
  return (
    <form>
      <div class="mb-3">
        <label>Title</label>
        <input type="text" class="form-control" placeholder="enter title" />
      </div>
      <div class="mb-3">
        <label>Author</label>
        <input type="text" class="form-control" placeholder="enter author" />
      </div>
      <button type="submit" class="btn btn-primary">
        Add
      </button>
    </form>
  );
};

export default AddBook;

리스트 Form

// client/src/components/Book.js
import React from 'react';

const Book = () => {
  return (
    <a
      href="#"
      class="list-group-item list-group-item-action"
      aria-current="true"
    >
      <div class="d-flex w-100 justify-content-between">
        <h5 class="mb-1">title</h5>
      </div>
      <p class="mb-1">author</p>
      <button>🗑️</button>
    </a>
  );
};

export default Book;

작성된 UI

참고문헌
class ApolloClient
https://www.apollographql.com/docs/react/api/core/ApolloClient/
Bootstrap
https://getbootstrap.kr/docs/5.1/getting-started/introduction/

0개의 댓글