Last active
November 3, 2019 18:53
-
-
Save zaydek-old/d7fd7b4655fe8f1faf62dd1e7eda9d4f to your computer and use it in GitHub Desktop.
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
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