[Apollo] 2장. React Apollo

Apollo 써보기

출처 : Apollo 공식 레퍼런스

목차


React Apollo

client
  .query({
    query: gql`
      {
        rates(currency: "USD") {
          currency
        }
      }
    `
  })
  .then(result => console.log(result));

Connect your client to React

const App = () => (
  <ApolloProvider client={client}>
    <div>
      <h2>My first Apollo app 🚀</h2>
    </div>
  </ApolloProvider>
);

Request Data

function ExchangeRates() {
  const { loading, error, data } = useQuery(gql`
    {
      rates(currency: "USD") {
        currency
        rate
      }
    }
  `);

  if (loading) return <p>Loading...</p>; // loading 중이라던가...
  if (error) return <p>Error :(</p>; // error가 났을  이렇게 쳐리해주면 된다.

  // 결과적으로 data가 잘 들어오면 이 부분이 실행된다!
  return data.rates.map(({ currency, rate }) => (
    <div key={currency}>
      <p>
        {currency}: {rate}
      </p>
    </div>
  ));
}

+) ApolloClient 옵션들