Skip to content

Instantly share code, notes, and snippets.

@zaydek zaydek/App.js
Created Nov 4, 2019

Embed
What would you like to do?
import React from "react"
const GraphQLContext = React.createContext()
const useQuery = (query, variables) => useQueryOrMutation(query, variables)
const useMutation = (query, variables) => useQueryOrMutation(query, variables)
function useQueryOrMutation(query, variables = {}) {
const { url, headers, credentials } = React.useContext(GraphQLContext)
const [isLoading, setIsLoading] = React.useState(false)
const [data, setData] = React.useState(null)
const [status, setStatus] = React.useState(null)
const [didError, setDidError] = React.useState(false)
const handleQuery = async () => {
setIsLoading(true)
const resp = await fetch(url, {
headers,
credentials,
method: "POST",
body: JSON.stringify({ query, variables })
})
setIsLoading(false)
setStatus({ code: resp.status, text: resp.statusText })
if (!resp.ok) {
setDidError(true)
return
}
const json = await resp.json()
setData(json.data)
}
return { handleQuery, isLoading, data, status, didError }
}
function Main(props) {
const { handleQuery, ...query } = useQuery(`
query {
sessions(userID: "u-J2cViDCqVzK") {
sessionID
}
}
`)
return (
<main>
<div className="m:2">
<div className="p-x:0.4 p-y:1 flex -r -x:center w:8 b:gray-100 br:0.4 pointer" onClick={e => handleQuery()}>
<p className="fs:1.1">
Press me!
</p>
</div>
</div>
<div className="m:2">
{query.isLoading
? (
<React.Fragment>
<div className="m-y:0.2 p-x:0.4 p-y:1 flex -r -x:center w:24 b:gray-100">
<p className="fs:1.1">
<br />
</p>
</div>
<div className="m-y:0.2 p-x:0.4 p-y:1 flex -r -x:center w:24 b:gray-50">
<p className="fs:1.1">
<br />
</p>
</div>
</React.Fragment>
)
: query.didError
? query.status.code + " " + query.status.text
: (
query.data && query.data.sessions.map(each => (
<div key={each.sessionID} className="m-y:0.2 p-x:0.4 p-y:1 flex -r -x:center w:24 b:gray-100">
<p className="fs:1.1">
{each.sessionID}
</p>
</div>
)
)
)
}
</div>
</main>
)
}
function App(props) {
return (
<GraphQLContext.Provider value={{
url: "http://localhost:8000/graphql",
headers: { "Content-Type": "application/json" },
credentials: "same-origin"
}}>
<Main />
</GraphQLContext.Provider>
)
}
export default App
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.