APOLLO CLIENT

서정준·2022년 7월 28일
0

Apollo GraphQL

목록 보기
2/2
post-thumbnail

1. Initialize ApolloClient

In index.js, let's first import the symbols we need from @apollo/client:

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

Next we'll initialize ApolloClient

const client = new ApolloClient({
  uri: 'https://flyby-gateway.herokuapp.com/',
  cache: new InMemoryCache(),
});
  • uri:
    specifies the URL of our GraphQL server.
  • cache:
    is an instance of InMemoryCache, which Apollo Client uses to cache query results after fetching them.

2. Connect your client to React

You connect Apollo Client to React with the ApolloProvider component.

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

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

3. Create a GraphQL query

Remember to wrap query strings in the gql function to parse them into query documents

 const GET_MOVIE = gql`
    query Query($movieId: String!) {
        movie(id: $movieId) {
          id
          title
      
    }
  }
`;

4. Create a component

Inside it, we'll pass our GET_MOVIE query to the useQuery hook:

export default function Movie() {
    const {id} = useParams()
    const {
      data,
      loading,
      client: { cache },
    } = useQuery(GET_MOVIE, {
      variables: {
        movieId: id,
      },
    });
  	if (loading) {
        return <h1>loading...</h1>
    }
    return <h1>{data.movie.title}</h1>
   
}
  • As our query executes and the values of loading, error, and data change, the Movie component can intelligently render different UI elements according to the query's state

  • The variables option is an object that contains all of the variables we want to pass to our GraphQL query :

    아래 variables를 GET_MOVIE query로 전달한다.

    variables: {
            movieId: id,
          }

출처

https://www.apollographql.com/docs/react/get-started/#step-3-initialize-apolloclient

https://www.apollographql.com/docs/react/data/queries/

profile
통통통통

0개의 댓글