Introduction to
by
Erick Escriba Arango
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.
- 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 integrationgraphql
: Also parses your GraphQL queriesgraphql-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')
)
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>
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>
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>;
}