Skip to content

Instantly share code, notes, and snippets.

@anthonyshort
Last active February 16, 2019 16:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonyshort/bc7586e79df00ac945173044ad31cc70 to your computer and use it in GitHub Desktop.
Save anthonyshort/bc7586e79df00ac945173044ad31cc70 to your computer and use it in GitHub Desktop.
React hooks + Apollo client
import useQuery from './useQuery'
import gql from 'graphql-tag'
type Props = {
projectId: string
}
export default function Project(props: Props) {
const { data, loading } = useQuery({
query: gql`
query($id: ID!) {
getProject(id: $id) {
name
}
}
`,
variables: {
id: props.projectId
}
}, [props.projectId])
if (loading) return <div>Loading...</div>
return <div>Project: {data.getProject.name}</div>
}
import { useState, useContext, useEffect, useMemo } from 'react'
import ApolloContext from './context/apollo'
import ApolloClient from 'apollo-client'
export default function useQuery(options, deps) {
const client = useContext(ApolloContext)
// Keep the observable around unless the dependencies change.
const observableQuery = useMemo(() => {
return client.watchQuery(options)
}, deps || [])
// The current result of the query in the cache
const [currentResult, setResult] = useState(observableQuery.currentResult())
// Then subscribe the query whenever the cache changes
useEffect(
() => {
const subscription = observableQuery.subscribe(setResult)
return () => subscription.unsubscribe()
},
[observableQuery]
)
return currentResult
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment