Getting Started With React And Apollo GraphQL

Create React App, and add apollo graphql to the application

GraphQL is a way to send data over HTTP and is often presented as a revolutionary new way to think about APIs and seen as the successor of REST (Representational State Transfer). Indeed GraphQL is able to overcome major shortcomings of REST.
GraphQL can be user in any application, web application or mobile app. In this tutorial you’ll learn how to use GraphQL in a React web application. To make use of GraphQL inside your React project we’ll be using the React Apollo library. Setting Up The Project To get started we first need to setup a new React project. The easiest way to do so is to use create-react-app. This script creates a new React project with zero build configuration. The project’s website can be found at https://github.com/facebook/create-react-app.
To make use of create-react-app you simply need to make sure that Node.js is installed on your system. There is no need to install create-react-app before using it. Instead the Node.js npx command can be used in the following way:
$ npx create-react-app react-graphql $ cd react-graphql $ npm start

This is initiating a new basic React project in the newly created project folder react-graphql. By using the npm start command the live-reloading development web server is started and the output of the default React project can be accessed in the browser:
CRA Default App
CRA Default App

Installing Dependencies The next step is to install needed dependencies. The following packages needs to be installed:
  • apollo-boost: Package containing everything you need to set up Apollo Client
  • react-apollo: View layer integration for React
  • graphql-tag: Necessary for parsing your GraphQL queries
  • graphql: Also parses your GraphQL queries

The installation of these dependencies can be done by using the following NPM command:
$ npm install apollo-boost react-apollo graphql-tag graphql

Exploring The Initial Project Structure Having installed the dependencies we’re ready to take a look at the initial project structure:
The important parts of the project are located in the src folder. The main entry point of the React application can be found in index.js. The code contained in this file is making sure that App component is rendered out to the DOM element with ID root.
The implementation of App component can be found in App.js. Creating An Instance Of ApolloClient In order to be able to access a GraphQL service from our React application we need to create an instance of ApolloClient first. This is done in App.js by adding the following code:
import ApolloClient from "apollo-boost"; const client = new ApolloClient({ uri: "[Insert URI of GraphQL endpoint]" });
First ApolloClient is imported from the apollo-boost library. A new instance of ApolloClient is created and stored in client. To create a new instance of ApolloClient you need to pass a configuration object to the constructor. This object must contain the uri property. The value of this property must be replaced which the URI of the GraphQL endpoint which should be accessed. Creating A GraphQL Endpoint https://launchpad.graphql.com/vm8mjvrnv3. This Launchpad exposes a GraphQL Online Courses API which we will be using for the following implementation steps. The corresponding endpoint of that Launchpad is

https://vm8mjvrnv3.lp.gql.zone/graphql, so that the value of the uri property needs to be set to that value:
import ApolloClient from "apollo-boost"; const client = new ApolloClient({ uri: "https://vm8mjvrnv3.lp.gql.zone/graphql" });
Connecting ApolloClient To Your React App Having established a connection to the GraphQL endpoint by using ApolloClient we now need to connect the instance of ApolloClient to the React app. To do so, please make sure to add the following lines of code in App.js: import { ApolloProvider } from "react-apollo";
... const App = () => ( <ApolloProvider client={client}> <div> <h2>My first Apollo app</h2> </div> </ApolloProvider> );
Fist ApolloProvide is imported from the react-apollo library. The <ApolloProvider> element is then used in the component's JSX code and is containing the template code which is used to render the component. Using Query Component To Request Data
Within the src folder create a new file Courses.js and insert the following code:
import React from 'react'; import { Query } from "react-apollo"; import gql from "graphql-tag"; const Courses = () => ( <Query query={gql` { allCourses { id title author description topic url } } `} > {({ loading, error, data }) => { if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return data.allCourses.map((
{ id, title, author, description, topic, url }) => ( <div key={id}> <p>{`${title} by ${author}`}</p> </div> )); }} </Query> ); export default Courses;
This is the implementation of the Courses component. To retrieve data from the GraphQL endpoint this component makes use of another component from the React Apollo library: Query. The Query component makes it extremely easy to embed the GraphQL query directly in the JSX code of the component. Furthermore the Query component contains a callback method which is invoked once the GraphQL query is executed.
Here we’re using the JavaScript map method to generate the HTML output for every single course record which is available in data.allCourses.
Adding A Course Component So far the output of courses is done within the Courses component. In the next step we’re going to introduce a new component to our project: Course. This component should then contain the code which is needed to output a single course. Once this component is available in can be used in Coursescomponent. First let’s add a new file Course.js to the project and insert the following lines of code:
import React from 'react'; const Course = (props) => ( <div key={props.course.id}> <p>{`${props.course.title} by ${props.course.author}`}
</p> </div> ); export default Course;
The implementation of this component is quite simple. The current course is handed over to Course component as a property and is available via props.course. In order to make use of Course component in Courses component we first need to make sure that it’s imported in file Courses.js:
import Course from './Course';
Now this component can be used to output each course inside the callback function which is passed to the call of map:
return data.allCourses.map((currentCourse) => ( <Course course={currentCourse} /> ));

The final result should then look like
The final result should then look like

Conclusion

With the release of React Apollo 2.1 it’s easier than ever to configure and connect Apollo to your React application. By using the brand new Query component you’re able to embed the GraphQL query inside your component. Using higher order components (like before) is no longer needed.

Never miss a post from Gufran Mirza, when you sign up for Ednsquare.