SlideShare a Scribd company logo
Graph QL
Problems with REST API
GET id -------------------> data
GET id2 -------------------> more data
GET data.id ------------------> even more data
Multiple Round Trips
● In order to descent into the object graph, multiple
round trips to the server are required.
● Critical for Mobile Environment
Over fetching
Unless specifically
designed,
you might receive needless
information
Compatibility and Versioning
http://api.myservice.com/v1/users
http://api.myservice.com/v2/users
http://api.myservice.com/v3/users
.
.
Backend APIs
are storage-centric
Front-end APIs
are product-centric
Graph Application Layer Query Language
(not Storage Query Language)
“A better solution that can replace restful server and mvc framework”
Basically JSON without the values
No custom endpoints
Clients ask exactly what they want
person:{ name:, address: }
Graph QL
● User-defined type system - “schema”
● Server describes what data is available
● Clients describe what data they require
● User-defined data fetching (“how do I get an article”)
● Front end request independent to backend
How Graph QL
Works
GraphQL has a type system
Three main “types” required to get an
endpoint up and running.
1. A type for the model
2. A type for the query
3. A type for the schema
In reality, it is more complex than this.
(forget about it for now)
Our Data
var goldbergs = {
1: {
character: "Beverly Goldberg",
actor: "Wendi McLendon-Covey",
role: "matriarch",
traits: "embarrassing, overprotective",
id: 1
},
2: {
character: "Murray Goldberg",
actor: "Jeff Garlin",
role: "patriarch",
traits: "gruff, lazy",
id: 2
},
3: {
character: "Erica Goldberg",
actor: "Hayley Orrantia",
role: "oldest child",
traits: "rebellious, nonchalant",
id: 3
},
4: {
character: "Barry Goldberg",
actor: "Troy Gentile",
role: "middle child",
traits: "dim-witted, untalented",
id: 4
},
5: {
character: "Adam Goldberg",
actor: "Sean Giambrone",
role: "youngest child",
traits: "geeky, pop-culture obsessed",
id: 5
},
6: {
character: "Albert 'Pops' Solomon",
actor: "George Segal",
role: "grandfather",
traits: "goofy, laid back",
id: 6
}
}
Model Type
Model Type is pretty much a mirror image
of each Goldberg in our goldbergs data
--------->
var goldbergType = new GraphQLObjectType({
name: "Goldberg",
description: "Member of The Goldbergs",
fields: {
character: {
type: GraphQLString,
description: "Name of the character",
},
actor: {
type: GraphQLString,
description: "Actor playing the character",
},
role: {
type: GraphQLString,
description: "Family role"
},
traits: {
type: GraphQLString,
description: "Traits this Goldberg is known for"
},
id: {
type: GraphQLInt,
description: "ID of this Goldberg"
}
}
});
1. Create a new instance of GraphQLObjectType, “Goldberg”
2. Under “fields”: Each “type” indicates the type expected
(e.g. string (GraphQLString) for character, int (GraphInt) for id.)
3. “description” fields are good for self-documentation
Query Type
The query type tells how we will query
our data
var queryType = new GraphQLObjectType({
name: "query",
description: "Goldberg query",
fields: {
goldberg: {
type: goldbergType,
args: {
id: {
type: GraphQLInt
}
},
resolve: function(_, args){
return getGoldberg(args.id)
}
}
}
});
function getGoldberg(id) {
return goldbergs[id]
}
1. Query Type is an instance of GraphQLObjectType, it just serves
a different purpose.
2. Create a new query field called goldberg and set its “type” to the
goldbergType we created earlier. Our new goldberg field will accept
an id as an assignment.
3. When we resolve our query we return the output of a function
getGoldberg()
Schema Type
Schema type combines them all together.
/* creating schema instance */
var schema = new GraphQLSchema({
query: queryType
});
/* serve our schema */
var graphQLServer = express();
graphQLServer.use('/', graphqlHTTP({ schema: schema,
graphiql: true }));
graphQLServer.listen(8080);
console.log("The GraphQL Server is running.")
{
goldberg ( id : 2 ) {
id,
character
}
}
{
“data” : {
“goldberg” : {
“id” : 2,
“character” : “Murray Goldberg”
}
}
Let’s Test
Go to GraphiQL IDE and test it yourself.
(GraphiQL IDE is just like postman of RESTful API for GraphQL)
React and
Redux
Let’s delete the “hello world” from
static/index.html and add a new message
using React in index.js:
| -- app
| -- actions
| -- components
| -- reducers
In the “reducers” folder we’ll create a new
file called reducer.js where we’ll work on
our reducer function.
import React from "react";
import ReactDOM from "react-dom";
const Main = React.createClass({
render: () => {
return (
<div>
<p>hello react!</p>
</div>
)
}
});
ReactDOM.render(
<Main />,
document.getElementById("example")
);
React and
Redux
We’ll be using the Immutable module for
our state so that we can form some good
habits.
Our state has two fields — one to let us
know if we are in the middle of a
query/awaiting a response from the server
and another that contains the response
data.
Next we plug our immutableState into a
reducer function:
import Immutable from "immutable";
const immutableState = Immutable.Map({
fetching: false,
data: Immutable.Map({})
})
--------------------------------------------------
export const queryReducer = (state = immutableState,
action) => {
switch (action.type) {
case "STARTING_REQUEST":
return state.set("fetching", true);
case "FINISHED_REQUEST":
return state.set("fetching", false)
.set("data",
Immutable.Map(action.response.data.goldberg));
default:
return state
}
}
Store
Back in index.js we want to create a store
out of our reducer and feed it to our main
component.
We’ll need to import the reducer we just
created along with some helpers from
redux and react-redux.
We also need the redux-thunk middleware
to help us later on when we need to make
some requests.
import React from "react";
import ReactDOM from "react-dom";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import { queryReducer } from
"./app/reducers/reducers.js";
import thunkMiddleware from "redux-thunk";
/* First, we apply the redux-thunk middleware:*/
const createStoreWithMiddleware = applyMiddleware(
thunkMiddleware
)(createStore)
/* Then we wrap our Main component in the Redux
Provider and pass our queryReducer into
createStoreWithMiddleware.*/
ReactDOM.render(
<Provider
store={createStoreWithMiddleware(queryReducer)}>
<Main />
</Provider>,
document.getElementById("example")
);
Actions
In the “actions” folder we’ll create a new
file called actions.js.
We need to create two actions to dispatch
to our reducer,
one for “STARTING_REQUEST”
and one for “FINISHED_REQUEST”:
const startingRequest = () => {
return {
type: "STARTING_REQUEST"
}
}
const finishedRequest = (response) => {
return {
type: "FINISHED_REQUEST",
response: response
}
}
Actions
The great thing about the redux-thunk
middleware we applied to our store earlier
is that when an action returns a function
that function is injected with dispatch().
We’ll get to use dispatch() twice in a new
action called getGraph:
When getGraph() is called we dispatch
startingRequest() to indicate the start of a
new query. We then begin the async
request (note the “application/graphql”
content type in the header) and when our
query is complete we dispatch
finishedRequest() with the results of our
query.
export const getGraph = (payload) => {
return dispatch => {
dispatch(startingRequest());
return new Promise(function(resolve, reject) {
let request=new XMLHttpRequest();
request.open("POST", "/graphql", true);
request.setRequestHeader("Content-Type",
"application/graphql");
request.send(payload);
request.onreadystatechange = () => {
if (request.readyState === 4) {
resolve(request.responseText)
}
}
}).then(response =>
dispatch(finishedRequest(JSON.parse(response))))
}
}
Component
For now we’ll create an empty Query
component:
We need to hook up our component with
our store and the dispatch method by
creating a container component and using
the react-redux connect() helper.
import React from ‘react’;
import { connect } from ‘react-redux’;
import { getGraph } from ‘../actions/actions.js’;
let Query = React.createClass({
render() {
return (
<div>
</div>
)
}
});
const mapStateToProps = (state) => {
return {
store: state
}
};
export const QueryContainer = connect(
mapStateToProps
)(Query);
let Query = React.createClass({
componentDidMount() {
this.props.dispatch(
getGraph("{goldberg(id: 2) {id, character, actor}}")
);
}
});
Component
We’ll also add the elements that our
response data will fill and a button to
submit additional queries. We want to
know if we are in the middle of a query so
we’ll grab our fetching field from our state
and display it on the page.
let Query = React.createClass({
componentDidMount() {
this.props.dispatch(
getGraph("{goldberg(id: 2) {id, character, actor}}")
);
},
render() {
let dispatch = this.props.dispatch;
let fetchInProgress =
String(this.props.store.get('fetching'));
let queryText;
let goldberg = this.props.store.get('data').toObject();
return (
<div>
<p>Fetch in progress: {fetchInProgress}</p>
<h3>{ goldberg.character }</h3>
<p>{ goldberg.actor }</p>
<p>{ goldberg.role }</p>
<p>{ goldberg.traits }</p>
<input ref={node => {queryText = node}}></input>
<button onClick={() => {
dispatch(getGraph(queryText.value))}
}>
query
</button>
</div>
)
}
});
Component
With that done, the last thing we have to
do is plug our QueryContainer component
into our Main component.
In index.js:
import { QueryContainer } from “./app/components/Query.js”;
// And replace “hello react!”
const Main = () => {
return (
<div>
<QueryContainer />
</div>
)
};
● https://learngraphql.com/basics/introduction
● https://medium.com/@thisbejim/getting-started-with-redux-and-graphql-
8384b3b25c56#.x08ia9y7m
Resources used in this
Presentation
Go to GraphiQL IDE and test it yourself.
(GraphiQL IDE is just like postman of RESTful API for GraphQL)

More Related Content

What's hot

GraphQL
GraphQLGraphQL
GraphQL IndyJS April 2016
GraphQL IndyJS April 2016GraphQL IndyJS April 2016
GraphQL IndyJS April 2016
Brad Pillow
 
GraphQL
GraphQLGraphQL
GraphQL
Joel Corrêa
 
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
Seven Peaks Speaks
 
Intro to GraphQL
 Intro to GraphQL Intro to GraphQL
Intro to GraphQL
Rakuten Group, Inc.
 
Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)
Rafael Wilber Kerr
 
An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQL
valuebound
 
GraphQL & Relay
GraphQL & RelayGraphQL & Relay
GraphQL & Relay
Viacheslav Slinko
 
GraphQL + relay
GraphQL + relayGraphQL + relay
GraphQL + relay
Cédric GILLET
 
GraphQL With Relay Part Deux
GraphQL With Relay Part DeuxGraphQL With Relay Part Deux
GraphQL With Relay Part Deux
Brad Pillow
 
Graphql
GraphqlGraphql
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
Rodrigo Prates
 
Taking Control of your Data with GraphQL
Taking Control of your Data with GraphQLTaking Control of your Data with GraphQL
Taking Control of your Data with GraphQL
Vinci Rufus
 
GraphQL Search
GraphQL SearchGraphQL Search
GraphQL Search
Artem Shtatnov
 
Apollo Server
Apollo ServerApollo Server
Apollo Server
NodeXperts
 
Graphql
GraphqlGraphql
Graphql
Niv Ben David
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
Amazon Web Services
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architectureAdding GraphQL to your existing architecture
Adding GraphQL to your existing architecture
Sashko Stubailo
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
Amazon Web Services
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits togetherGraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits together
Sashko Stubailo
 

What's hot (20)

GraphQL
GraphQLGraphQL
GraphQL
 
GraphQL IndyJS April 2016
GraphQL IndyJS April 2016GraphQL IndyJS April 2016
GraphQL IndyJS April 2016
 
GraphQL
GraphQLGraphQL
GraphQL
 
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
 
Intro to GraphQL
 Intro to GraphQL Intro to GraphQL
Intro to GraphQL
 
Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)
 
An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQL
 
GraphQL & Relay
GraphQL & RelayGraphQL & Relay
GraphQL & Relay
 
GraphQL + relay
GraphQL + relayGraphQL + relay
GraphQL + relay
 
GraphQL With Relay Part Deux
GraphQL With Relay Part DeuxGraphQL With Relay Part Deux
GraphQL With Relay Part Deux
 
Graphql
GraphqlGraphql
Graphql
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Taking Control of your Data with GraphQL
Taking Control of your Data with GraphQLTaking Control of your Data with GraphQL
Taking Control of your Data with GraphQL
 
GraphQL Search
GraphQL SearchGraphQL Search
GraphQL Search
 
Apollo Server
Apollo ServerApollo Server
Apollo Server
 
Graphql
GraphqlGraphql
Graphql
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architectureAdding GraphQL to your existing architecture
Adding GraphQL to your existing architecture
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits togetherGraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits together
 

Viewers also liked

[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우
NAVER D2
 
Adversarial learning for neural dialogue generation
Adversarial learning for neural dialogue generationAdversarial learning for neural dialogue generation
Adversarial learning for neural dialogue generation
Keon Kim
 
개발자라면, 블로그
개발자라면, 블로그개발자라면, 블로그
개발자라면, 블로그
HyunSeob Lee
 
Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기
raccoony
 
[123] electron 김성훈
[123] electron 김성훈[123] electron 김성훈
[123] electron 김성훈
NAVER D2
 
Docker란 무엇인가? : Docker 기본 사용법
Docker란 무엇인가? : Docker 기본 사용법Docker란 무엇인가? : Docker 기본 사용법
Docker란 무엇인가? : Docker 기본 사용법
pyrasis
 
[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱
NAVER D2
 
React.js workshop
React.js workshopReact.js workshop
React.js workshop
Pearl McPhee
 
OpenNMT
OpenNMTOpenNMT
OpenNMT
Keon Kim
 
Бэкенд, фронтенд — всё смешалось (nodkz)
Бэкенд, фронтенд — всё смешалось (nodkz)Бэкенд, фронтенд — всё смешалось (nodkz)
Бэкенд, фронтенд — всё смешалось (nodkz)
Pavel Chertorogov
 
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
Pavel Chertorogov
 
Stock Prediction Using NLP and Deep Learning
Stock Prediction Using NLP and Deep Learning Stock Prediction Using NLP and Deep Learning
Stock Prediction Using NLP and Deep Learning
Keon Kim
 
재사용UI 컴포넌트설계
재사용UI 컴포넌트설계재사용UI 컴포넌트설계
재사용UI 컴포넌트설계
지수 윤
 
Attention mechanisms with tensorflow
Attention mechanisms with tensorflowAttention mechanisms with tensorflow
Attention mechanisms with tensorflow
Keon Kim
 
역시 Redux
역시 Redux역시 Redux
역시 Redux
Leonardo YongUk Kim
 
Front-End 개발의 괜찮은 선택 ES6 & React
Front-End 개발의 괜찮은 선택  ES6 & ReactFront-End 개발의 괜찮은 선택  ES6 & React
Front-End 개발의 괜찮은 선택 ES6 & React
지수 윤
 
React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작
Taegon Kim
 
Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까?
Kim Hunmin
 
[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔
NAVER D2
 
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
NAVER D2
 

Viewers also liked (20)

[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우
 
Adversarial learning for neural dialogue generation
Adversarial learning for neural dialogue generationAdversarial learning for neural dialogue generation
Adversarial learning for neural dialogue generation
 
개발자라면, 블로그
개발자라면, 블로그개발자라면, 블로그
개발자라면, 블로그
 
Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기
 
[123] electron 김성훈
[123] electron 김성훈[123] electron 김성훈
[123] electron 김성훈
 
Docker란 무엇인가? : Docker 기본 사용법
Docker란 무엇인가? : Docker 기본 사용법Docker란 무엇인가? : Docker 기본 사용법
Docker란 무엇인가? : Docker 기본 사용법
 
[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱
 
React.js workshop
React.js workshopReact.js workshop
React.js workshop
 
OpenNMT
OpenNMTOpenNMT
OpenNMT
 
Бэкенд, фронтенд — всё смешалось (nodkz)
Бэкенд, фронтенд — всё смешалось (nodkz)Бэкенд, фронтенд — всё смешалось (nodkz)
Бэкенд, фронтенд — всё смешалось (nodkz)
 
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
 
Stock Prediction Using NLP and Deep Learning
Stock Prediction Using NLP and Deep Learning Stock Prediction Using NLP and Deep Learning
Stock Prediction Using NLP and Deep Learning
 
재사용UI 컴포넌트설계
재사용UI 컴포넌트설계재사용UI 컴포넌트설계
재사용UI 컴포넌트설계
 
Attention mechanisms with tensorflow
Attention mechanisms with tensorflowAttention mechanisms with tensorflow
Attention mechanisms with tensorflow
 
역시 Redux
역시 Redux역시 Redux
역시 Redux
 
Front-End 개발의 괜찮은 선택 ES6 & React
Front-End 개발의 괜찮은 선택  ES6 & ReactFront-End 개발의 괜찮은 선택  ES6 & React
Front-End 개발의 괜찮은 선택 ES6 & React
 
React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작
 
Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까?
 
[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔
 
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
 

Similar to GraphQL, Redux, and React

Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
Christoffer Noring
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
MarcinStachniuk
 
JPA 2.0
JPA 2.0JPA 2.0
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in Java
MarcinStachniuk
 
GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0
Tobias Meixner
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primer
Bruce McPherson
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKitTaras Kalapun
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
Frost
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
VMware Tanzu
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
Martin Kleppe
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
Bruce McPherson
 
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"ITGinGer
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platforms
Ayush Sharma
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Sages
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Fwdays
 
Splitapp coding
Splitapp codingSplitapp coding
Splitapp coding
Kannan Selvam
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
croquiscom
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
Jairam Chandar
 

Similar to GraphQL, Redux, and React (20)

Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in Java
 
GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primer
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platforms
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"
 
Splitapp coding
Splitapp codingSplitapp coding
Splitapp coding
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
 

Recently uploaded

重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
vmemo1
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
Laura Szabó
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
harveenkaur52
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
keoku
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
CIOWomenMagazine
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
nhiyenphan2005
 
Search Result Showing My Post is Now Buried
Search Result Showing My Post is Now BuriedSearch Result Showing My Post is Now Buried
Search Result Showing My Post is Now Buried
Trish Parr
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Florence Consulting
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
uehowe
 
[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
hackersuli
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
zyfovom
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Brad Spiegel Macon GA
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
Trending Blogers
 
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
cuobya
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
7 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 20247 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 2024
Danica Gill
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
Javier Lasa
 

Recently uploaded (20)

重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
 
Search Result Showing My Post is Now Buried
Search Result Showing My Post is Now BuriedSearch Result Showing My Post is Now Buried
Search Result Showing My Post is Now Buried
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
 
[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
 
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
7 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 20247 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 2024
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
 

GraphQL, Redux, and React

  • 2. Problems with REST API GET id -------------------> data GET id2 -------------------> more data GET data.id ------------------> even more data
  • 3. Multiple Round Trips ● In order to descent into the object graph, multiple round trips to the server are required. ● Critical for Mobile Environment
  • 4. Over fetching Unless specifically designed, you might receive needless information
  • 7. Graph Application Layer Query Language (not Storage Query Language) “A better solution that can replace restful server and mvc framework”
  • 8. Basically JSON without the values No custom endpoints Clients ask exactly what they want person:{ name:, address: } Graph QL
  • 9. ● User-defined type system - “schema” ● Server describes what data is available ● Clients describe what data they require ● User-defined data fetching (“how do I get an article”) ● Front end request independent to backend How Graph QL Works
  • 10. GraphQL has a type system Three main “types” required to get an endpoint up and running. 1. A type for the model 2. A type for the query 3. A type for the schema In reality, it is more complex than this. (forget about it for now)
  • 11. Our Data var goldbergs = { 1: { character: "Beverly Goldberg", actor: "Wendi McLendon-Covey", role: "matriarch", traits: "embarrassing, overprotective", id: 1 }, 2: { character: "Murray Goldberg", actor: "Jeff Garlin", role: "patriarch", traits: "gruff, lazy", id: 2 }, 3: { character: "Erica Goldberg", actor: "Hayley Orrantia", role: "oldest child", traits: "rebellious, nonchalant", id: 3 }, 4: { character: "Barry Goldberg", actor: "Troy Gentile", role: "middle child", traits: "dim-witted, untalented", id: 4 }, 5: { character: "Adam Goldberg", actor: "Sean Giambrone", role: "youngest child", traits: "geeky, pop-culture obsessed", id: 5 }, 6: { character: "Albert 'Pops' Solomon", actor: "George Segal", role: "grandfather", traits: "goofy, laid back", id: 6 } }
  • 12. Model Type Model Type is pretty much a mirror image of each Goldberg in our goldbergs data ---------> var goldbergType = new GraphQLObjectType({ name: "Goldberg", description: "Member of The Goldbergs", fields: { character: { type: GraphQLString, description: "Name of the character", }, actor: { type: GraphQLString, description: "Actor playing the character", }, role: { type: GraphQLString, description: "Family role" }, traits: { type: GraphQLString, description: "Traits this Goldberg is known for" }, id: { type: GraphQLInt, description: "ID of this Goldberg" } } }); 1. Create a new instance of GraphQLObjectType, “Goldberg” 2. Under “fields”: Each “type” indicates the type expected (e.g. string (GraphQLString) for character, int (GraphInt) for id.) 3. “description” fields are good for self-documentation
  • 13. Query Type The query type tells how we will query our data var queryType = new GraphQLObjectType({ name: "query", description: "Goldberg query", fields: { goldberg: { type: goldbergType, args: { id: { type: GraphQLInt } }, resolve: function(_, args){ return getGoldberg(args.id) } } } }); function getGoldberg(id) { return goldbergs[id] } 1. Query Type is an instance of GraphQLObjectType, it just serves a different purpose. 2. Create a new query field called goldberg and set its “type” to the goldbergType we created earlier. Our new goldberg field will accept an id as an assignment. 3. When we resolve our query we return the output of a function getGoldberg()
  • 14. Schema Type Schema type combines them all together. /* creating schema instance */ var schema = new GraphQLSchema({ query: queryType }); /* serve our schema */ var graphQLServer = express(); graphQLServer.use('/', graphqlHTTP({ schema: schema, graphiql: true })); graphQLServer.listen(8080); console.log("The GraphQL Server is running.")
  • 15. { goldberg ( id : 2 ) { id, character } } { “data” : { “goldberg” : { “id” : 2, “character” : “Murray Goldberg” } } Let’s Test Go to GraphiQL IDE and test it yourself. (GraphiQL IDE is just like postman of RESTful API for GraphQL)
  • 16. React and Redux Let’s delete the “hello world” from static/index.html and add a new message using React in index.js: | -- app | -- actions | -- components | -- reducers In the “reducers” folder we’ll create a new file called reducer.js where we’ll work on our reducer function. import React from "react"; import ReactDOM from "react-dom"; const Main = React.createClass({ render: () => { return ( <div> <p>hello react!</p> </div> ) } }); ReactDOM.render( <Main />, document.getElementById("example") );
  • 17. React and Redux We’ll be using the Immutable module for our state so that we can form some good habits. Our state has two fields — one to let us know if we are in the middle of a query/awaiting a response from the server and another that contains the response data. Next we plug our immutableState into a reducer function: import Immutable from "immutable"; const immutableState = Immutable.Map({ fetching: false, data: Immutable.Map({}) }) -------------------------------------------------- export const queryReducer = (state = immutableState, action) => { switch (action.type) { case "STARTING_REQUEST": return state.set("fetching", true); case "FINISHED_REQUEST": return state.set("fetching", false) .set("data", Immutable.Map(action.response.data.goldberg)); default: return state } }
  • 18. Store Back in index.js we want to create a store out of our reducer and feed it to our main component. We’ll need to import the reducer we just created along with some helpers from redux and react-redux. We also need the redux-thunk middleware to help us later on when we need to make some requests. import React from "react"; import ReactDOM from "react-dom"; import { createStore, applyMiddleware } from "redux"; import { Provider } from "react-redux"; import { queryReducer } from "./app/reducers/reducers.js"; import thunkMiddleware from "redux-thunk"; /* First, we apply the redux-thunk middleware:*/ const createStoreWithMiddleware = applyMiddleware( thunkMiddleware )(createStore) /* Then we wrap our Main component in the Redux Provider and pass our queryReducer into createStoreWithMiddleware.*/ ReactDOM.render( <Provider store={createStoreWithMiddleware(queryReducer)}> <Main /> </Provider>, document.getElementById("example") );
  • 19. Actions In the “actions” folder we’ll create a new file called actions.js. We need to create two actions to dispatch to our reducer, one for “STARTING_REQUEST” and one for “FINISHED_REQUEST”: const startingRequest = () => { return { type: "STARTING_REQUEST" } } const finishedRequest = (response) => { return { type: "FINISHED_REQUEST", response: response } }
  • 20. Actions The great thing about the redux-thunk middleware we applied to our store earlier is that when an action returns a function that function is injected with dispatch(). We’ll get to use dispatch() twice in a new action called getGraph: When getGraph() is called we dispatch startingRequest() to indicate the start of a new query. We then begin the async request (note the “application/graphql” content type in the header) and when our query is complete we dispatch finishedRequest() with the results of our query. export const getGraph = (payload) => { return dispatch => { dispatch(startingRequest()); return new Promise(function(resolve, reject) { let request=new XMLHttpRequest(); request.open("POST", "/graphql", true); request.setRequestHeader("Content-Type", "application/graphql"); request.send(payload); request.onreadystatechange = () => { if (request.readyState === 4) { resolve(request.responseText) } } }).then(response => dispatch(finishedRequest(JSON.parse(response)))) } }
  • 21. Component For now we’ll create an empty Query component: We need to hook up our component with our store and the dispatch method by creating a container component and using the react-redux connect() helper. import React from ‘react’; import { connect } from ‘react-redux’; import { getGraph } from ‘../actions/actions.js’; let Query = React.createClass({ render() { return ( <div> </div> ) } }); const mapStateToProps = (state) => { return { store: state } }; export const QueryContainer = connect( mapStateToProps )(Query); let Query = React.createClass({ componentDidMount() { this.props.dispatch( getGraph("{goldberg(id: 2) {id, character, actor}}") ); } });
  • 22. Component We’ll also add the elements that our response data will fill and a button to submit additional queries. We want to know if we are in the middle of a query so we’ll grab our fetching field from our state and display it on the page. let Query = React.createClass({ componentDidMount() { this.props.dispatch( getGraph("{goldberg(id: 2) {id, character, actor}}") ); }, render() { let dispatch = this.props.dispatch; let fetchInProgress = String(this.props.store.get('fetching')); let queryText; let goldberg = this.props.store.get('data').toObject(); return ( <div> <p>Fetch in progress: {fetchInProgress}</p> <h3>{ goldberg.character }</h3> <p>{ goldberg.actor }</p> <p>{ goldberg.role }</p> <p>{ goldberg.traits }</p> <input ref={node => {queryText = node}}></input> <button onClick={() => { dispatch(getGraph(queryText.value))} }> query </button> </div> ) } });
  • 23. Component With that done, the last thing we have to do is plug our QueryContainer component into our Main component. In index.js: import { QueryContainer } from “./app/components/Query.js”; // And replace “hello react!” const Main = () => { return ( <div> <QueryContainer /> </div> ) };
  • 24. ● https://learngraphql.com/basics/introduction ● https://medium.com/@thisbejim/getting-started-with-redux-and-graphql- 8384b3b25c56#.x08ia9y7m Resources used in this Presentation Go to GraphiQL IDE and test it yourself. (GraphiQL IDE is just like postman of RESTful API for GraphQL)