The best way to retrieve data from GraphQL in React is to use a library such as Apollo Client, which makes working with GraphQL easier.
This tutorial is simple and easy to follow:
1. Install Apollo Client and GraphQL
First, install the required dependencies:
npm install @apollo/client graphql
2. Set up Apollo Client
Create an Apollo Client instance and set it up in your React app. Typically, this is done in the src/index.js or src/App.js.
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import App from './App';
// Create Apollo Client
const client = new ApolloClient({
uri: 'https://my-graphql-endpoint.com/graphql', // Replace with your GraphQL endpoint
cache: new InMemoryCache(),
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);
3. Fetch data using useQuery Hook
In your component, use the useQuery hook to fetch data.
import React from 'react';
import { useQuery, gql } from '@apollo/client';
// Define your query
const GET_DATA = gql`
query {
data {
id
name
}
}
`;
const DataComponent = () => {
const { loading, error, data } = useQuery(GET_DATA);
if (loading) return <p>Loading</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h2>Data Fetching:</h2>
{data && data.map(item => (
<div key={item.id}>
<p>{item.name}</p>
</div>
))}
</div>
);
};
export default DataComponent;
4. Run your React app
Make sure your React app is running. It will fetch the data from the GraphQL endpoint and display it accordingly.