How to access fetched data through graphql query?

by dalton_moen , in category: Javascript , 4 months ago

How to access fetched data through graphql query?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , 4 months ago

@dalton_moen 

To access fetched data through a GraphQL query, you can use the query itself to define the shape of the data you want to receive. Here's a brief example using a GraphQL query:

1
2
3
4
5
6
7
query {
  user(id: 1) {
    id
    name
    email
  }
}


In this query, we are fetching the user with ID 1 and requesting their ID, name, and email fields. Once you send this query to your GraphQL server, you will receive a response that includes the data you requested.


You can access this data in your frontend application code by parsing the response and extracting the data you need. For example, in JavaScript you could do something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
fetch('https://your-graphql-server', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query: 'query { user(id: 1) { id name email } }' })
})
.then(response => response.json())
.then(data => {
  const user = data.data.user;
  console.log(user.id, user.name, user.email);
})
.catch(error => console.error(error));


This code sends a POST request to your GraphQL server with the query to fetch the user data. Once the response is received, it parses the JSON data and extracts the user object, allowing you to access the individual fields like ID, name, and email.


By structuring your GraphQL queries in a way that matches the shape of the data you need, you can easily access the fetched data in your frontend application code.