DEV Community


Adding GraphQL to React

I've been tinkering with computers since I was a teen. I'm currently pivoting from my current role as Tech Support manager to Full Stack Web Developer. I'm actively seeking employment in the field.
・1 min read

To add GraphQL, add some libraries.

yarn add apollo-boost react-apollo graphql

Now you can use these libraries to pull the data from the backend and do whatever you need to with it. In this example, we’re building an e-commerce app, so we’ll be pulling the data that populates the store from a GraphQL database.What we’re doing is in the code comments below.

import React from "react";
import { Query } from "react-apollo";
import { gql } from "apollo-boost";

import CollectionsOverview from "./collections-overview.component";
import Spinner from "../spinner/spinner.component";

// query the DB.
//The gql tag and backtics let us use the GraphQL style of queries inside of our JavaScript
const GET_COLLECTIONS = gql`
    collections {
      items {

const CollectionsOverviewContainer = () => (
  // Query returns a function. On that function is going to be an object that holds a number of different properties
  // Wrap the Query component around whatever component you want to receive the data
  <Query query={GET_COLLECTIONS}>
    {/* destructure off the things you want to get from the object to use */}
    {({ loading, data }) => {
      if (loading) return <Spinner />;
      return <CollectionsOverview collections={data.collections} />; //data is the top level key for what's returned from GraphQL in this case, so data.collections will return the collections

export default CollectionsOverviewContainer;

Discussion (0)