Created
October 8, 2019 14:19
-
-
Save klummy/783902ec747aa7804ed433872833bde5 to your computer and use it in GitHub Desktop.
WIP
This file contains hidden or 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
/** | |
* 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