Blog>
Snippets

Fetching Data with useQuery and GraphQL

Showcase how to use the `useQuery` hook from React Query to fetch data from a GraphQL API, including handling loading, error, and data states.
import { useQuery, gql } from '@apollo/client';
First, import the useQuery hook and gql function from @apollo/client for creating GraphQL queries.
const GET_DATA = gql`\n  query GetData {\n    data {\n      id\n      value\n    }\n  }\n`;
Define your GraphQL query using gql. This example fetches an object with an id and value from your API.
function DataFetcher() {\n  const { loading, error, data } = useQuery(GET_DATA);\n\n  if (loading) return \<p>Loading...\</p>;\n  if (error) return \<p>Error: {error.message}\</p>;\n\n  return (\n    \<div>\n      {data && \<p>{data.value}</p>}\n    \</div>\n  );\n}
Create a React component that uses the useQuery hook to execute the GraphQL query. Handle loading, error, and data states to display relevant information or the fetched data.