Blog>
Snippets

Fetching chart data with useQuery hook

Show how to use the useQuery hook from Apollo Client to fetch data for charts, handling loading and error states.
import { useQuery } from '@apollo/client';
import gql from 'graphql-tag';
First, import useQuery from Apollo Client and gql to parse your query string into a query document.
const GET_CHART_DATA = gql`
  query GetChartData {
    chartData {
      label
      value
    }
  }
`;
Define your GraphQL query. This example fetches data suitable for a chart with labels and values.
function ChartComponent() {
  const { loading, error, data } = useQuery(GET_CHART_DATA);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  // Render your chart component using the data
  return (
    <div>{/* Your Chart Implementation Here */}</div>
  );
}
Use the useQuery hook within your component to fetch the data. Handle loading and error states before rendering the chart with the fetched data.