Blog>
Snippets

Transforming GraphQL data for TanStack React Charts

Present how to transform data fetched from GraphQL into a format suitable for TanStack React Charts, focusing on mapping operations.
const fetchGraphQLData = async () => {
  // Fetch data from a GraphQL API
  const response = await fetch('YOUR_GRAPHQL_ENDPOINT', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: '{ yourQuery { dataField1, dataField2 } }' })
  });
  const { data } = await response.json();
  return data.yourQuery;
}
This piece of code is responsible for fetching data from a GraphQL endpoint. You need to replace 'YOUR_GRAPHQL_ENDPOINT' with your actual GraphQL endpoint and adjust the query according to your schema. This function returns the data in the structure provided by your GraphQL server.
const transformDataForCharts = (fetchedData) => {
  // Transform data into a format suitable for TanStack React Charts
  const transformedData = fetchedData.map(item => ({
    x: item.dataField1,
    y: item.dataField2
  }));
  return transformedData;
}
This function takes the fetched GraphQL data as input and transforms it into a format that TanStack React Charts can utilize. Specifically, it maps each item of the input data to an object with 'x' and 'y' properties. You might need to adjust 'dataField1' and 'dataField2' to the fields returned by your GraphQL query.
// Example usage
(async () => {
  const fetchedData = await fetchGraphQLData();
  const chartData = transformDataForCharts(fetchedData);
  console.log(chartData); // This is the transformed data ready to be used with TanStack React Charts
})();
This is an example of how the above functions could be used together. It fetches data from a GraphQL API, transforms the data for TanStack React Charts, and logs the transformed data to the console. This is where you would typically pass 'chartData' to your chart component.