Last active
April 29, 2020 09:52
-
-
Save reecelucas/7f5f1589b29c2a0d6e3da6fa1fe4a393 to your computer and use it in GitHub Desktop.
Simple util for querying a GraphQL service using the fetch API
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
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(); | |
}; |
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
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