Skip to content

Instantly share code, notes, and snippets.

@reecelucas
Last active April 29, 2020 09:52
Show Gist options
  • Save reecelucas/7f5f1589b29c2a0d6e3da6fa1fe4a393 to your computer and use it in GitHub Desktop.
Save reecelucas/7f5f1589b29c2a0d6e3da6fa1fe4a393 to your computer and use it in GitHub Desktop.
Simple util for querying a GraphQL service using the fetch API
const fetchGraphQL = async ({ url, query, variables, headers }) => {
const response = await fetch(url, {
method: "POST",
headers: {
...headers,
"Content-Type": "application/json"
},
body: JSON.stringify({ query, variables })
});
// Get the response as JSON
return response.json();
};
const COUNTRY_CAPITAL_QUERY = `
query countryCapital($code: ID!) {
country(code: $code) {
capital
}
}
`;
fetchGraphQL({
url: "https://countries.trevorblades.com/",
query: COUNTRY_CAPITAL_QUERY,
variables: { code: "GB" },
})
.then((response) => {
const { data } = response;
console.log(data.country.capital);
})
.catch((error) => {
console.error(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment