Evolution of writing GraphQL Client for React
Since year 2015 when Facebook made GraphQL
public, it has changed a lot. Specially once Apollo
team started development for GraphQL
.
This post is going to talk about progress for GraphQL
client for React.
Facebook developed Relay client for React
Facebook came up with graphql
javascript module which was javascript implementation of GraphQL specification. Facebook also came up with Relay
which was client for React.
Relay client for React
Relay gives QueryRenderer
React component to make graphql
API call. Following is sample example.
// UserTodoList.js
// @flow
import React from 'react';
import PropTypes from 'prop-types';
import {graphql, QueryRenderer} from 'react-relay';const environment = /* defined or imported above... */;type Props = {
userID: string,
};export default class UserTodoList extends React.Component<Props> {
render() {
const {userID} = this.props;return (
<QueryRenderer
environment={environment}
query={graphql`
query UserQuery($userID: ID!) {
node(id: $userID) {
id
}
}
`}
variables={{userID}}
render={({error, props}) => {
if (error) {
return <div>Error!</div>;
}
if (!props) {
return <div>Loading...</div>;
}
return <div>User ID: {props.node.id}</div>;
}}
/>
);
}
}
Apollo team developed client for React
Apollo react client has two parts
- Configure Apollo client
- API to interact with GraphQL
In last few years, Apollo team worked very hard and developed easy to use client for GraphQL. It is divided into following two releases
- Apollo GraphQL client 1.0 series
- Apollo GraphQL client 2.0 series
New GraphQL client 2.0 is compatible with 1.0 release as well. In 2.0, Higher Order Component design was replaced by pure React component. Following are new features in 2.x.x
Query
as pure react component overgraphql
Higher Order Component.Mutation
as pure react componentgraphql
Higher Order Component.Subscription
as pure react componentgraphql
Higher Order Component.ApolloConsumer
as pure react component overwithApollo
Higher Order Component.
Configure Apollo Client
Fetch data from GraphQL
Update data from GraphQL