From ea8a14cc2856c7e8fc5a3a076ba2f6d15fdd7adf Mon Sep 17 00:00:00 2001 From: Trevor Blades Date: Fri, 9 Nov 2018 12:34:54 -0800 Subject: [PATCH] Add a practical example --- README.md | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 71 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3e80626..f21d7f1 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,7 @@ A public GraphQL API for information about countries, continents, and languages. 1. The codes used to key the objects in the original data are available as a `code` property on each item returned from the API. 2. The `continent` and `languages` properties are now objects and arrays of objects, respectively. -Check out the [playground](https://countries.trevorblades.com) to explore the schema and test out some queries. - -## Example +## Writing queries ```graphql { @@ -46,3 +44,73 @@ Check out the [playground](https://countries.trevorblades.com) to explore the sc } } ``` + +Check out the [playground](https://countries.trevorblades.com) to explore the schema and test out some queries. + +## Example + +A practical use of this API is to create a country select input that doesn't require you to include a large dataset of country info in your bundle. + +In this example, we'll be using [React](https://reactjs.org/) and the [Apollo](https://apollographql.com) GraphQL client. First, we'll install all of our dependencies: + +```shell +$ npm install react react-dom react-apollo apollo-boost graphql graphql-tag +``` + +50.1 KB with `countries-list` +14.2 KB with Countries GraphQL + +```js +import React from 'react'; +import ReactDOM from 'react-dom'; +import ApolloClient from 'apollo-boost'; + +const client = new ApolloClient({ + uri: 'https://countries.trevorblades.com' +}); + +const GET_COUNTRIES = gql` + { + countries { + name + code + } + } +`; + +class App extends Component { + state = { + country: '' + }; + + onCountryChange = event => + this.setState({country: event.target.value}); + + render() { + return ( + + + {({loading, error, data}) => { + if (loading) return

Loading...

; + if (error) return

{error.message}

; + return ( + + ); + }} +
+
+ ); + } +} + +ReactDOM.render(, document.getElementById('root')); +```