@apollo/client

송승찬·2020년 10월 18일
0

TIL

목록 보기
48/52

이제는 @apollo/client하나만 설치하면 apollo-boost react-apollo @react/apollo-hooks apollo-client를 대체할 수 있다.

즉,@apollo/client graphql 이거면 아폴로 클라이언트를 가지고 graphQL과 데이터를 주고 받을 준비가 끝난다.

설치

npm i @apollo/client graphql

사용하는 법

1. 클라이언트 생성

client.js

import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://48p1r2roz4.sse.codesandbox.io',
  cache: new InMemoryCache()
});
export default client;

2.클라이언트와 리액트 앱의 연결

App.js

import React from 'react';
import { render } from 'react-dom';
import ExchangeRates from './ExchangeRates';
import client from './client';

import { ApolloProvider } from '@apollo/client';

function App() {
  return (
    <ApolloProvider client={client}>
      <div>
        <h2>Hi Apollo 🚀</h2>
        <ExchangeRates />
      </div>
    </ApolloProvider>
  );
}

render(<App />, document.getElementById('root'));

3. 데이터 요청(grpahql통해 가져오기)

ExchangeRates.js

import { useQuery, gql } from '@apollo/client';

const EXCHANGE_RATES = gql`
  query GetExchangeRates {
    rates(currency: "USD") {
      currency
      rate
    }
  }
`;

export default function ExchangeRates() {
  const { loading, error, data } = useQuery(EXCHANGE_RATES);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return data.rates.map(({ currency, rate }) => (
    <div key={currency}>
      <p>
        {currency}: {rate}
      </p>
    </div>
  ));
}

ExchangeRates component within your App component from the previous example, you'll first see a loading indicator on the page, followed by data when it's ready. Apollo Client automatically caches this data when it comes back from the server, so you won't see a loading indicator if you run the same query again.
즉,데이터를 처음 가져올 때는 loading Indicator가 보이지만, 같은 값을 서버에서 다시 가져올때는 아폴로 클라이언트가 자동으로 캐시해오기에 loading Indicator가 다시 뜨지X

개인적으로 헷갈렸던 것들 요소들은 다음과 같았다.

gql

import {gql} fron '@apollo/client'

gql function to parse the query string into a query document.
즉, gql이 쿼리 스트링을 쿼리 다큐멘트형태로 바꿔서 graphql이 쓸 수 있게
해준다.

ApolloProvider

ApolloProvier로 컴포넌트를 감싸줘야 graphQL데이터에 접근이 가능해진다.리액트의 <Context.Provider>와 비슷하다

출처
https://www.apollographql.com/docs/react/get-started/#request-data

profile
superfly

0개의 댓글