Skip to content

Instantly share code, notes, and snippets.

@dagoof
Created January 25, 2018 05:43
Show Gist options
  • Save dagoof/d16ec6058b7dfa596a5c62c192f881ea to your computer and use it in GitHub Desktop.
Save dagoof/d16ec6058b7dfa596a5c62c192f881ea to your computer and use it in GitHub Desktop.
5 minutes with apollo
import React, { Component } from 'react'
import { InMemoryCache } from 'apollo-cache-inmemory'
import ApolloClient from 'apollo-client'
import { ApolloProvider, graphql } from 'react-apollo'
import { HttpLink } from 'apollo-link-http'
import gql from 'graphql-tag'
const client = new ApolloClient({
ssrMode: true,
link: new HttpLink({ uri: 'https://graphql-pokemon.now.sh' }),
cache: new InMemoryCache(),
shouldBatch: true,
})
const MY_QUERY = gql`
query($name: String!) {
pokemon(name: $name) {
id
name
types
}
}
`
const ViewPokemon = props => {
return (
<div>
<h1>{props.name}</h1>
<p>{props.id}</p>
<ul>
{props.types.map(type => <li key={`${props.id}-${type}`}>{type}</li>)}
</ul>
</div>
)
}
const WithData = (Component, selector) => ({ data }) => {
switch (true) {
case data.loading:
return <p>Loading...</p>
case !!data.error:
return <p>something went wrong ... :(</p>
case !selector(data):
return null
default:
return <Component {...selector(data)} />
}
}
const Pokemon = graphql(MY_QUERY, {
options: ({ name }) => ({
variables: { name },
}),
})(WithData(ViewPokemon, data => data.pokemon))
class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<div>
<Pokemon name="Snorlax" />
<Pokemon name="Ditto" />
<Pokemon name="Venonat" />
<Pokemon name="Snorlax" />
<Pokemon name="Flareon" />
<Pokemon name="Frogtown" />
<Pokemon name="Moltres" />
</div>
</ApolloProvider>
)
}
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment