Last active
February 16, 2019 16:04
-
-
Save anthonyshort/bc7586e79df00ac945173044ad31cc70 to your computer and use it in GitHub Desktop.
React hooks + Apollo client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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