Created
November 4, 2019 08:01
-
-
Save zaydek-old/e386cb9af9a089e29f5f96d41b16821a 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
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