Connecting app with GraphQL server - ScalaConsultants/react-example-app GitHub Wiki

This project is using GraphQL client Apollo to fetch data from server (simple database on graph.cool).

Installation

npm install react-apollo --save

Connecting with server

import { ApolloClient, createNetworkInterface , ApolloProvider} from 'react-apollo'
Creating connection with GraphQL server
const networkInterface = createNetworkInterface({
  uri: 'https://api.graph.cool/simple/v1/cj3mzkoyv3b3e0189nnt1gh3v'  // link to server
})

const client = new ApolloClient({
  networkInterface: networkInterface
})
Creating a provider

We need to add Apollo provider on elements which will have access to GraphQL data. If we want add this for whole app we can wrap React Router provider as in this example:

  <ApolloProvider client={client}>
    <Provider store={store}>
      [...]
    </Provider>
  </ApolloProvider>

Usage

Import for components using GraphQL data
import { gql, graphql } from 'react-apollo'
Creating query
const queryName = gql`
  query {
    allUsers { 
      id
      name
    }
  }`
Connecting component

We need to use graphql() function to connet component with GraphQL data:

const ComponentWithData = graphql(queryName)(ComponentName)

If we are using Redux we just pass to connect connected with GraphQL component:

export default connect(mapStateTopProps)(ComponentWithData)
Using fetched data

Now we can use fetched data in connected component via props.data for example:

props.data.allUsers

We can (should) also use data field loading and error to check if data is loaded or if we got some errors. For example we can write:

  if(data.loading){
    return <div>LOADING</div>
  }

before we want use fetched data to omit asking for undefined data errors.

Cheat Sheet

  • fetching all Products

GraphQL query
const productInfo = gql`
  query {
    allProducts { 
      id
      name
      price
      category {
        name
      }
    }
  }`

Note that if our type name is Product to call for all we write allProducts

  • fetching specific Product

GraphQL query
const productDetails = gql`
  query ProductQuery($id: ID!){
    Product(id: $id) { 
      id
      name
      price
      desc
      category {
        name
      }
    }
  }`
Connecting component
const ProductDetailsData = graphql(productDetails, {
  options: (ownProps) => ({
    variables: {
      id: ownProps.match.params.id
    }
  })
})(ProductDetails)
⚠️ **GitHub.com Fallback** ⚠️