Workshop Setup

These slides (open them on your computer):
https://slides.com/jasonbahl-1/wcoc

or

Optional, but helpful:

GraphiQL

Super Powered Single page apps
with react, wordpress & graphql

WordCamp orange county 2017

Me.

  • Senior WordPress Engineer at Digital First Media in Denver, CO
  • Denver native
  • WordPress Developer for 8+ years
  • I love WordPress, and Open Source in general
  • Creator and maintainer of the WPGraphQL plugin

Things this workshop

will cover.

  • Intro to React and GraphQL
  • Build a Single Page App with:
    • Styled Components
    • Routing
    • Redux state management
    • GraphQL queries managed by Apollo Client
    • Customize the WPGraphQL Schema

The Modern Web

The Modern Web

The Modern Web

The Modern Web

Reactive and Stateful

What is REACT?

  • Open Source JavaScript library created and maintained by Facebook
     
  • Declarative, component-based architecture
     
  • Uses JSX which compiles down to JavaScript
     
  • Uses "props" and "state" to manage state (keep truth out of the DOM)

How React Works

First things first...what is DOM?

How React Works

Let's Build something!

Intro to Components and Styled Components

Adding routes

Layout & Nested Routes

Populating our app with data

What is Graphql?

A query language for your API

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete

and understandable description of the data in your API, gives

clients the power to ask for exactly what they need and

nothing more, makes it easier to evolve APIs over time, and

enables powerful developer tools.

http://graphql.org/

  • Query Language for APIs using existing data
  • Complete & understandable description of the data in your API
  • Client controls the model (exactly what is asked for in the shape it was asked)
  • Easier versioning & powerful tooling

GraphQl Query Language

{
     me {
          name
     }
}

{

     data: {

          me: {

               name: "Jason Bahl"

          }

     }
}

GraphQL Query

GraphQL Result

GraphQl Query Language

query GetPost {
  post( id: "..." ) {
    title
    link
    bylines {
      name
    }
  }
}
{
  data: {
    post: {
      title: "Hello World!"
      link: "http://site.com/hello-world"
      bylines: [
        {
          name: "John Doe",
        },
        {
          name: "Jane Doe",
        }
      ]
    }
  }
}

What does graphql mean?

GRAPH = APPLICATION DATA GRAPH

QL = QUERY LANGUAGE

GRAPH != GRAPH DATABASES

GRAPH != GRAPH Search

WP Application data graph

Post

Byline

"Jane Doe"

"Hello World"

name

title

Post

"Goodbye Mars"

title

Byline

"John Doe"

name

Graphql lets us pick
trees out of the graph

Pick Trees out of the graph

query GetPost {
  post( id: "..." ) {
    title
    link
    bylines {
      name
    }
  }
}
{
  data: {
    post: {
      title: "Hello World!"
      link: "http://site.com/hello-world"
      bylines: [
        {
          name: "John Doe",
        },
        {
          firstName: "Jane Doe",
        }
      ]
    }
  }
}

WP Application data graph

Post

Byline

Jane Doe

"Hello World"

name

title

Post

"Goodbye Mars"

title

Byline

John Doe

name

That doesn't look

like a tree?

WP Application data graph

Post

Byline

Jane Doe

"Hello World"

name

title

Byline

John Doe

name

bylines

bylines

Traversal

RootQuery

post( id: "..." )

title

query {

 

 

 

}

post( id: "..." ) {
   
}

title

do_graphql_request()

get_post( $id )

$post->post_title

Client controls the model

query { 
  posts {
    edges {
      node {



        












      }
    }
  }
}
        author {
          name
          avatar(size: 50) {
            url
          }
        }
        followLink
        title
        featuredImage(width: 300) {
          url
        }
        excerpt
        site {
          name
          link
        }

Demo Time!

Demos:

  • documentation
  • postList
  • variables
  • nested relations
  • pages
  • pagesAuthorsPosts
  • multiple root queries
  • node query
  • aliasing
  • fragments
  • introspection (via GraphQL Vogager)

Connecting Apollo

Connecting to GraphQL

Customize our Graphql schema

<?php

use WPGraphQL\Types;

function wcoc_add_release_date_field( $fields ) {

	$fields['releaseDate'] = [
		'type'        => Types::string(),
		'description' => __( 'The date the film was released', 'graphql-workshop' ),
		'resolve'     => function( \WP_Post $post ) {

			$release_date = get_post_meta( $post->ID, 'release_date', true );
			$timestamp    = strtotime( $release_date );

			return ( false !== $timestamp ) ? date( 'M j, Y', $timestamp ) : null;
		},
	];

	return $fields;

}

add_filter( 'graphql_post_fields', 'wcoc_add_release_date_field', 10, 1 );

Paginating data

Easier versioning

Amazing Tooling

Amazing Tooling

Should I Use GraphQL?

App Size / Complexity

Effort

Line of "fed-up"

Amazing Tooling

Available for Wordpress today

(pre-release)

GraphQl Query Language

query GetPost($id: Int!) {
  post(id: $id) {
    title
    link
    bylines {
      firstName
      lastName
      email
    }
  }
}
variables: {
  "id": "cG9zdDoxMTc4"
}
Operation type
Operation name
Variable Definitions
Selection set on query
Selection set on post

https://goo.gl/4PbVrq

GraphQl SCHEMA

Query & Mutation Types

http://graphql.org/learn/schema/

schema: {
  query: Query
  mutation: Mutation
}

Every GraphQL service has a query type and may or may not have a mutation type. These types are the same as a regular object type, but they are special because they define the entry point of every GraphQL query

GraphQl SCHEMA

Complete & understandable description of data

  • Query & Mutation Types
  • Object Types & Fields
  • Arguments
  • Scalar Types
  • Enumeration Types
  • Lists & Non-Null
  • Union Types
  • Input Types

http://graphql.org/learn/schema/

GraphQl SCHEMA

Object Types & Fields

http://graphql.org/learn/schema/

Type Post {

  id: Id!

  title: String

  postId: Int!

  bylines: [ Byline ]

}

Type Byline {

  firstName: String! 

  lastName: String

  email: String

  posts: [ Post ]

}

The most basic components of a GraphQL schema are object types, which just represent a kind of object you can fetch from your service, and what fields it has

GraphQl SCHEMA

Arguments:

Every field on a GraphQL object type can have zero or more arguments, for example the length field below

http://graphql.org/learn/schema/

Type Byline {

  firstName: String! 

  lastName: String

  email: String

  posts( first: Int! ): [ Post ]

}

GraphQl SCHEMA

Scalar Types:

At some point fields have to resolve to some concrete data. That's

where the scalar types come in: they represent the leaves of the query

http://graphql.org/learn/schema/

Int, Float, String, Boolean, ID

Custom defined (date? email? url? other?)

GraphQl SCHEMA

Enumeration Types:

Also called Enums, enumeration types are a special kind of scalar that is restricted to a particular set of allowed values

http://graphql.org/learn/schema/

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

GraphQl SCHEMA

LISTS & NON-NULL Types:

Non-null types will throw an error if a null value is returned,

or a null value is used for the input argument. 

 

Lists indicate that an array will be returned or an array

is expected for input of an argument.

http://graphql.org/learn/schema/

Type Post {

  id: Id!

  bylines: [ Byline ]

}

GraphQl SCHEMA

Union Types:

Union Types can define on of many types that can be returned where

the returned type is not known until the query is run. 

 

For example, in WordPress, an item in the media library can have a parent that could be a post, page or custom post type.

http://graphql.org/learn/schema/

Type MediaItem {

  id: ID!

  parent: Post | Page

}

GraphQl SCHEMA

Input Types:

Input types define the shape of what can be input into arguments

or mutations. This is particularly valuable where input values

might consistof entire objects or other nested values

 

In WordPress, an example might be the

arguments for tax_query or meta_query

http://graphql.org/learn/schema/

Super Powered Single Page Apps with React, WordPress and GraphQL

By Jason Bahl

Super Powered Single Page Apps with React, WordPress and GraphQL

  • 2,118
Loading comments...

More from Jason Bahl