Skip to content

Instantly share code, notes, and snippets.

@zaydek-old
Last active November 3, 2019 18:53
Show Gist options
  • Save zaydek-old/d7fd7b4655fe8f1faf62dd1e7eda9d4f to your computer and use it in GitHub Desktop.
Save zaydek-old/d7fd7b4655fe8f1faf62dd1e7eda9d4f to your computer and use it in GitHub Desktop.
let endpoint = "http://localhost:8000/graphql"
let headers = { "Content-Type": "application/json" }
let credentials = "same-origin"
function useQuery(query, variables = {}) {
const [loading, setLoading] = React.useState(false)
const [data, setData] = React.useState(null)
const [status, setStatus] = React.useState(0)
const [statusText, setStatusText] = React.useState("")
const handleQuery = async () => {
setLoading(true)
const resp = await fetch(endpoint, {
headers,
credentials,
method: "POST",
body: JSON.stringify({ query, variables })
})
setStatus(resp.status)
setStatusText(resp.statusText)
if (!resp.ok) {
return
}
let json = null
try {
json = await resp.json()
} catch (e) {
setStatus(500)
setStatusText("Internal Server Error")
return
}
setData(json.data)
setLoading(false)
}
return { handleQuery, loading, data, status, statusText }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment