Skip to content

Instantly share code, notes, and snippets.

@zaydek zaydek/naiveUseQuery.js
Last active Nov 3, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.