[GraphQL #2] GraphQL로 React앱 만들기

in #kr6 years ago (edited)

이번에는 GraphQL과 React를 사용하여 웹앱을 개발합니다. apollo-graphql에서 제공하는 react-apollo를 사용하면 웹앱을 정말 쉽게 개발 할 수 있습니다. [GraphQL #1] GraphQL로 API 서버 만들기에서 이어지는 내용입니다.

우리는 크롬 브라우저에서 개발할 것입니다. 개발하기 전에 아래 크롬 브라우저 확장 프로그램을 설치해주세요.

Apollo Client Developer Tools 설치

https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm

React Developer Tools 설치

https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi

apollo dev tools

이 글은 니꼴라스님의 동영상 강의 GraphQL, Apollo로 웹앱 만들기 를 학습하고 정리한 내용입니다.


* * *

create-react-app 설치


create-react-app를 설치한다.

$ npm install -g create-react-app

create-react-app를 사용하려면 Node 8.10.0 이상이어야 한다.


create-react-app 도구를 사용하기 위해 node를 업데이트한다.

$ brew update
$ brew upgrade node

참고로 나는 MacOS라서 homebrew를 사용하여 node를 업데이트했다.



프로젝트 생성


create-react-app 도구를 사용하여 프로젝트를 생성한다.

$ npx create-react-app movieql-client

create-react-app를 사용한 프로젝트 생성은 npx, npm, yarn 으로 생성하는 방법이 있다. 자세한 내용은 여기를 참고한다.



필요한 모듈 설치


react router를 사용하기 위해 react-router-dom를 설치한다.

$ yarn add react-router-dom


그리고 react-apollo를 설치한다.

$ yarn add apollo-boost react-apollo graphql-tag graphql



구현하기


apolloClient.js 파일을 생성한다.

import ApolloClient from "apollo-boost";

const client = new ApolloClient({
  uri: 'http://localhost:4000'
});

export default client;

ApolloClient 객체의 uri에는 GraphQL API 서버 주소를 등록한다.

여기서 사용한 graphql API 서버 소스는 깃허브에 업로드되어 있다.
https://github.com/anpigon/movieql/


queries.js 파일을 생성한다.

import gql from "graphql-tag";

export const HOME_PAGE = gql`
  query {
    movies(limit:50, rating: 7) {
      id
      title
      rating
      medium_cover_image
    }
  }
`;

GraphQL API 서버에서 데이터를 조회하기 위한 쿼리문을 입력한다.


Home.js 파일 생성한다.

import React from "react";
import { Query } from "react-apollo";
import { HOME_PAGE } from "./queries";

const Home = () => (
  <Query query={HOME_PAGE}>
    {
      ({ loading, data, error }) => {
        if(loading) return <span>loading</span>;
        if(error) return <span>ERROR</span>;
        return data.movies.map(movie => (
          <h2 key={movie.id}>
            {movie.title} / {movie.rating}
          </h2>
        ));
      }
    }
  </Query>
);

export default Home;

앞에서 만든 HOME_PAGE 쿼리를 사용하여 데이터를 조회한다. titlerating 데이터를 가져와서 화면에 출력할 것이다.


App.js 파일을 수정한다.

import React, { Component } from 'react';
import { HashRouter as Router, Route } from "react-router-dom";
import { ApolloProvider } from "react-apollo";
import client from "./apolloClient";
import Home from "./Home";

class App extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        <Router>
          <main>
            <Route exact={true} path={"/"} component={Home} />
          </main>
        </Router>
      </ApolloProvider>
    );
  }
}

export default App;

ApolloProvider 컴포넌트를 사용하여 Router를 감싼다. 그리고 라우트 /Home 컴포넌트를 등록한다.


아래는 결과 화면이다.

구현하고 보니 코드 라인 수가 몇줄 안된다. 내 생각에는 apollo-graphql를 사용하면 개발시간을 절약할 수 있을 것 같다.

끝.


Sponsored ( Powered by dclick )
바이트볼 주간 뉴스레터(11월 9일자), Delta 다이렉트 지원, 프리랜서 작가 채용, WCG 공헌자 천 명 돌파

바이트볼 주간 뉴스레터 2018. 11. 09 일자 소식을 전합니다. 이번 주 주요 내용은 다...

Sort:  

newbijohn님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^
newbijohn님의 [씽스팀 콘테스트] 나는코노가수다 2탄. 쇼미더스팀달라 콘테스트가 종료되었습니다. 총상금 100스팀! 총 참가자 21명!!

...하지 않고 받고 있으니 언제든지 문의 주세여~~(잘먹겠습니다!!)
1탄 참가자들의 씽스팀 보러 가즈아우리 anpigon개발 이사님이 만들어주셨어염~ >.<
_후원사(한 번 후원사는 영원한 후원사!!)https://s...

Congratulations @anpigon! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 2000 upvotes. Your next target is to reach 3000 upvotes.

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

SteemFest3 and SteemitBoard - Meet the Steemians Contest

Support SteemitBoard's project! Vote for its witness and get one more award!

ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ
웃음밖에 안나오는 이 문자들....ㅜㅜ

아름다운 문자입니다~ 보고 있으면 흐믓합니다.ㅋㅋ

꾸준함+성실함은=천재이십니다 당신은.

감사합니다.
이 바닥에서 살아남으려면 끊임없이 공부하고 기술을 연구해야한다고 생각합니다. 하지만 시간과 머리가 안따라주니 갈길이 멉니다.ㅠㅠ

Hi @anpigon!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your UA account score is currently 2.488 which ranks you at #16447 across all Steem accounts.
Your rank has improved 194 places in the last three days (old rank 16641).

In our last Algorithmic Curation Round, consisting of 255 contributions, your post is ranked at #190.

Evaluation of your UA score:
  • Only a few people are following you, try to convince more people with good work.
  • You have already convinced some users to vote for your post, keep trying!
  • Try to improve on your user engagement! The more interesting interaction in the comments of your post, the better!

Feel free to join our @steem-ua Discord server

GraphQL 요즘 관심있게 보고 있는데 잘 보고갑니다!!

지존코딩으로 유튜브 방송하시는 분이군요. 반갑습니다.

busy.pay 첫보팅 축하드려요ㅎㅎ

감사합니다~^0^ ㅋㄷㅋㄷ

잘 참고할게요.

gql 한번 사용해보세요.ㅋ 너무 좋습니다.

디클하구 갑니다 ^^

아름다운 문자입니다~^^ 디클릭 꾸욱~

디클릭 감사합니다~!

Coin Marketplace

STEEM 0.19
TRX 0.13
JST 0.030
BTC 60422.26
ETH 3311.81
USDT 1.00
SBD 2.37