GraphCMS with React: Connecting React Hooks & Apollo GraphQL

GraphQL is an Open Source schema query language that brings efficiency and utility to performing API (Application Programming Interface) calls across servers to Websites, Applications, and Software.

Developed by Facebook, a core feature of GraphQL’s ability to format queries with definable attributes and multiple relations that can be many or few. Mutating and subscribing to these queries can allow for continues fetch and update, as many CRUD (Create Read Update and Delete) functions of REST(Representational State Transfer) APIs, though with more precision and performance.

Content Management Systems as a Service

Content management is a lot of work and effort, building the schema to a database can be quite easy for the experience, setting up the template and rendering the content, not such a worry, but updating and managing that content & images is where it gets complex.

GraphCMS bridges the gap of building a content development interface for editing your content and supporting your schema markup. What also gets quite complex is setting up image hosting — this can be a deployed folder, a cloud service, or even behind a CDN, but streaming your connected content together is worth finding a CMS.

Getting started with GraphCMS, a service for content management with GraphQL APIs. Choosing the blog template has options for immediate integration prepared for Gatsby & NextJS, though React takes a bit more work, this can still be a helpful way establish a schema.

Connecting to a GraphQL API with React & Apollo GraphQL

Apollo GraphQL is a framework of software and features that helps developers build performant GraphQL services. In place of RESTful APIs with something such as Express and Mongoose, Apollo GraphQL combines the power of GraphQL with many frameworks.

Apollo GraphQL Client

Setting up the GraphQL client for fetching queried data in React requires a Page/Component, HOC (Higher Order Component), and a FC (Functional Component) in laymen the view, an iterator, and the iterated class.

First, in your terminal, install the Package via NPM.

npm install @apollo/client graphql

Then establish your your GraphQL Page.

import * as React from "react";import GraphQLHigherOrderComponent from "./GraphQLHigherOrderComponent";import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";const httpsLink = new ApolloClient({uri: "https://graphcms.com/",});const client = new ApolloClient({link: httpsLink,cache: new InMemoryCache(),});function GraphQLPage() {return (<ApolloProvider client={client}>    <GraphQLHigherOrderComponent /></ApolloProvider>);}export default GraphQLPage;

Once the GraphQL page/component has been established, there is now a GraphQL provider for accessing the returned data, within the lower components in the structure, via this client.

Making GraphQL API Queries with React & Apollo GraphQL

The Apollo GraphQL client is now streaming into the HOC so that React can recognize its output and turn it into props (properties) to pass through the functional component. The Apollo GraphQL client uses a custom ‘useQuery’ React hook to process the data stream and pass it into the later components.

Apollo GraphQL Query

First establish and set the query via GraphQL and Apollo GraphQL Client, since the query is to GraphCMS, the query should be set to fetch against the existing schema.

const POSTS_QUERY = gql`{posts {idtitleexcerpt}}`;

Then finish connecting the ApolloGraphQL client in the Higher Order Component, so that when the query is run, in this case, on-load of the page and mount of the component, the interface is populated with the result. In this scenario the iterator is created through React Props and passed by the JavaScript Map() function.

import * as React from "react";import GraphQLFunctionalComponent from "./GraphQLFunctionalComponent";import { useQuery, gql } from "@apollo/client";const POSTS_QUERY = gql`{posts {idtitleexcerpt}}`;const GraphQLHigherOrderComponent = () => {const { loading, error, data } = useQuery(POSTS_QUERY);if (loading) return "Loading...";if (error) return `Error! ${error.message}`;return (<>    {data.posts.map((index) => (        <GraphQLFunctionalComponent key={index.id} post={index} />    ))}</>);};export default GraphQLHigherOrderComponent;

The above Higher Order Component passes the query response downstream and populates the Functional Component with the content passed through the query, once the React Props have been set.

Populating User Interfaces with Apollo GraphQL Queries & React Hooks

React Props now encapsulate the data from upstream and render them into the functional components downstream. Establishing the same data fetched from the query, iterated into a composes format with props.

For these components to be rendered programmatically, the props themselves must be rendered in the template.

import * as React from "react";const GraphQLFunctionalComponent = (props) => {const { post } = props;return (    <>        <h1>{post.title}</h1>        <p>{post.excerpt}</p>    </>);};export default GraphQLFunctionalComponent;

Passing this data into the functional component, which simply utilizes the data in a template format completes the lifecycle of the React data stream from GraphQL Query & React Hook response.

Performant GraphQL Queries from GraphCMS with Apollo GraphQL

These queries can be created, managed, and fetched with GraphQL itself by establishing a similar markup, though requires additional configuration for passing data elements and transforming the response.

This pattern can be replicated and adapted to build routed components by adding additional packages such as React Router, which has its own hook built for ‘useParams()’, this allows for string concatenation via the url to populate, serve, and route React Components with dynamic data.

Establishing Higher Order Components & Functional Components promotes code reusability and enables a concise framework to follow this pattern, when adding in GraphQL mutations and subscriptions to enumerate queries.

Required Frameworks & Packages:

Additional Frameworks & Packages:

Thanks for Reading, Keep Querying!

Looking for more Software Development advice? Follow along on Twitter, GitHub, and LinkedIn — You can get in touch with me directly on Messenger. Visit online for the latest updates, news, and information at collectedview.io.

--

--

--

Full Stack Developer @IBM — Java, Spring, React, React Native, JavaScript, Node, NoSQL, Kubernetes & Cloud Native. (These Views Are My Own) collectedview.io

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Getting Started With JavaScript for Beginners

Build a Location-based Chatroom with Firebase and Vue.js —Geohash

Building My First Lightning Web Component (LWC) in Salesforce

Todo app in Javascript(Beginners Guide)

Few Important Things to Code in JavaScript

Create a calendar with React JS from scratch

Refactor Common CLI Tools

How To Create Animated FAQ Section With HTML, CSS and JavaScript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Joe Alongi

Joe Alongi

Full Stack Developer @IBM — Java, Spring, React, React Native, JavaScript, Node, NoSQL, Kubernetes & Cloud Native. (These Views Are My Own) collectedview.io

More from Medium

React State vs Redux State

Using Emotion in React App

This Week In React #92: Remix, MDX 2, Lifetime Analysis, Story of React, Quick Start Docs…

What is React Fiber and How It Helps You Build a High-Performing React Applications