Last active
May 12, 2019 06:58
-
-
Save cmmartin/9dc747d3c00d6fb4e9759532d4a98311 to your computer and use it in GitHub Desktop.
The simplest way to make a graphQL request in React
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
/** | |
* Usage: | |
* | |
* function Movie({ title = 'Inception' }) { | |
* const [data, loading, error] = useGraphQL('https://api.graph.cool/simple/v1/movies', ` | |
* query getMovie($title: String!) { | |
* Movie(title: $title) { | |
* releaseDate | |
* actors { | |
* name | |
* } | |
* } | |
* } | |
* `, | |
* { title }, | |
* [title] | |
* ) | |
* | |
* if (loading) return <p>loading...</p> | |
* | |
* if (error) return <p>{error.toString()}</p> | |
* | |
* return <pre>{JSON.stringify(data, null, 2)}</pre> | |
* } | |
*/ | |
import { useState, useEffect } from 'react' | |
import { request } from 'graphql-request' | |
export default function useGraphQL( | |
endpoint = '/graphql', | |
query, | |
variables, | |
inputs = [] | |
) { | |
const [data, setData] = useState(null) | |
const [loading, setLoading] = useState(false) | |
const [error, setError] = useState(null) | |
useEffect(() => { | |
setLoading(true) | |
request(endpoint, query, variables) | |
.then(result => { | |
setError(null) | |
setData(result) | |
}) | |
.catch(e => { | |
setError(e) | |
setData(null) | |
}) | |
.finally(() => { | |
setLoading(false) | |
}) | |
}, inputs) | |
return [data, loading, error] | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment