Skip to content

Instantly share code, notes, and snippets.

@klummy
Created October 8, 2019 14:19
Show Gist options
  • Save klummy/783902ec747aa7804ed433872833bde5 to your computer and use it in GitHub Desktop.
Save klummy/783902ec747aa7804ed433872833bde5 to your computer and use it in GitHub Desktop.
WIP
/**
* Hook based method to allow for making GraphQL requests easily.
* @param {string} query Query string
* @param {object} variables [Optional] Optional GraphQL parameters/variables
* @param {Array<any>} deps [Optional] Optional dependencies which when any of the values in the array changes, the request is retried. Ignored on the server
*/
export const useGraphql = (query, variables = {}, dependencies = []) => {
// Loading state if action is in progress
const [loading, setLoading] = useState(true);
// Error state
const [error, setError] = useState();
// Response from GraphQL query
const [response, setResponse] = useState();
const client = createClient()
const queryRequest = () => client.request(query, variables)
// Client side
useEffect(() => {
setLoading(true)
queryRequest()
.then((data) => {
setResponse(data)
})
.catch((err) => {
setError(err)
})
.finally(() => {
setLoading(false)
})
}, dependencies)
if (isServer()) {
return client.request(query, variables)
.then(res => {
return {
error,
loading,
response: res
}
})
.catch(errDetails => {
return {
error: errDetails,
loading,
response
}
})
// console.log('data => ', data);
// console.log('err => ', err);
// return {
// error: err,
// loading: false, // Loading is always false on SSR
// response: data
// }
}
return {
error,
loading,
response
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment