Created
July 8, 2019 17:58
-
-
Save ivanalejandro0/b360a7e19f0caa080602ba3f8a46c6f9 to your computer and use it in GitHub Desktop.
Temporary useQuery hook implementation
This file contains hidden or 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
/** | |
* React hook to execute an Apollo query and keep the data up to date according | |
* what's newest on the cache. | |
* | |
* @param { DocumentNode } query: the GraphQL query you want to run | |
* @param { Object } variables: the variables you want to interpolate on the query | |
* Note: you may want to memoize your object to prevent the query to run multiple times. | |
* | |
* Read more about param types on Apollo's watchQuery docs: | |
* https://www.apollographql.com/docs/react/api/apollo-client/#ApolloClient.watchQuery | |
* @returns { Object } an object with 3 properties: | |
* { data: (or undefined), loading: whether is loading or not, error: (or undefined) } | |
*/ | |
function useQuery(query, variables) { | |
const [state, setState] = useState({ loading: true }); | |
const handleNext = ({ data }) => setState({ data, loading: false }); | |
const handleError = (error) => setState({ error, loading: false }); | |
useEffect(() => { | |
// get client created for ApolloProvider | |
const client = getApolloClient(); | |
const observableQuery = client.watchQuery({ query, variables }); | |
const subscription = observableQuery.subscribe({ | |
next: handleNext, | |
error: handleError, | |
}); | |
return () => subscription.unsubscribe(); | |
}, [query, variables]); | |
return { ...state }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Relevant links:
Conversation about officially supporting hooks:
3rd party implementation being used for many people:
Official hooks support (in beta):