Skip to content

Instantly share code, notes, and snippets.

@cmmartin
Last active May 12, 2019 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmmartin/9dc747d3c00d6fb4e9759532d4a98311 to your computer and use it in GitHub Desktop.
Save cmmartin/9dc747d3c00d6fb4e9759532d4a98311 to your computer and use it in GitHub Desktop.
The simplest way to make a graphQL request in React
/**
* 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