Introduction to

Client

by

Erick Escriba Arango

graphql

Tools:

  • Apollo Client
  • Apollo Server
  • Apollo Graph Manager
  • Apollo Links

Client

Apollo Client es una biblioteca completa de administración de estado para aplicaciones JavaScript. Simplemente escriba una consulta GraphQL, y Apollo Client se encargará de solicitar y almacenar en caché sus datos, así como de actualizar su IU.

Features

  • Declarative data fetching: Write a query and receive data without manually tracking loading states
  • Excellent developer experience: Enjoy helpful tooling for TypeScript, Chrome DevTools, and VS Code
  • Designed for modern React: Take advantage of the latest React features, such as hooks
  • Incrementally adoptable: Drop Apollo into any JavaScript app seamlessly
  • Universally compatible: Use any build setup and any GraphQL API
  • Community driven: Share knowledge with thousands of developers, thanks to our active open source community
  • Zero config-caching: you get an intelligent cache out of the box with no additional configuration required.

Getting Started

  • yarn add apollo-boost @apollo/react-hooks graphql graphql-tag
  • apollo-boost: Package containing everything you need to set up Apollo Client
  • @apollo/react-hooks: React hooks based view layer integration
  • graphql: Also parses your GraphQL queries
  • graphql-tag: A JavaScript template literal tag that parses GraphQL queries
//index.js
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloProvider } from 'react-apollo'
import App from './App'
const client = new ApolloClient({
  link: createHttpLink({ uri: 'https://api.github.com/graphql' }),
  cache: new InMemoryCache()
})
ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('root')
)

useQuery

import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';

export const PLAYER = gql`
query Player ($id: Int!) {
  player(id: $id) {
    first_name
    last_name
  }
}
const Player = () => {
  const context = useContext(PlayerContext);
  const { data, loading, error } = useQuery(PLAYER, {
    variables: {id: context.activePlayerId
    }});
  if (error) {
    return error.message;
  }
  return (
    <React.Fragment>
      <h1>Player data</h1>
      { loading ? <p>Loading...</p> :
        <React.Fragment>
          <p>First name: {data.player.first_name}</p>
          <button onClick={() => context.setActivePlayerId(0)}>
           Return to players list
           </button>
        </React.Fragment>}
    </React.Fragment>

useMutation

import { useMutation } from '@apollo/react-hooks';
export const ADD_TODO = gql`
  mutation AddTodo($type: String!) {
    addTodo(type: $type) {
      id
      type
    }
  }
`;
const App = () => {
  let input;
  const [addTodo, { data }] = useMutation(ADD_TODO);
  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault();
          addTodo({ variables: { type: input.value } });
          input.value = '';
        }}>
        <input ref={node => { input = node; }} />
        <button type="submit">Add Todo</button>
      </form>
    </div>

useSubscription

yarn add apollo-link-ws subscriptions-transport-ws
const COMMENTS_SUBSCRIPTION = gql`
  subscription onCommentAdded($repoFullName: String!) {
    commentAdded(repoFullName: $repoFullName) {
      id
      content
    }
  }
`;
import { split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';

const httpLink = new HttpLink({
  uri: 'http://localhost:3000/graphql'
});

const wsLink = new WebSocketLink({
  uri: `ws://localhost:5000/`,
  options: {
    reconnect: true
  }
});
// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  httpLink,
);
function DontReadTheComments({ repoFullName }) {
  const { data: { commentAdded }, loading } = useSubscription(
    COMMENTS_SUBSCRIPTION,
    { variables: { repoFullName } }
  );
  return <h4>New comment: {!loading && commentAdded.content}</h4>;
}

Thanks