Open In App

Implementing GraphQL Queries using React Hooks & Apollo Client

Implementing GraphQL queries with React Hooks and Apollo Client involves setting up Apollo Client in your React application, defining GraphQL queries using useQuery hook, and accessing data from the GraphQL API in a declarative way. With Apollo Client, React Hooks like useQuery simplifies the process of fetching and managing data from a GraphQL server, offering a more efficient and organized approach to data fetching in React applications.

Prerequisites

Steps to Implement GraphQL Queries using Hooks & Apollo

Step 1: Create a reactJS application by using this command

npx create-react-app graphql

Step 2: Navigate to project directory

cd graphql

Step 3: Install the necessary packages/libraries in your project using the following commands.

npm install @apollo/client graphql

Project Structure:

react-str

The updated dependencies in package.json file will look like:

"dependencies": {
    "@apollo/client": "^3.9.6",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "graphql": "^16.8.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },

Approach to Implement GraphQL Queries using Hooks & Apollo:

Example: Illustration to Implement GraphQL Queries with React Hooks and Apollo Client.

/* index.css */

.App-header {
    font-size: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
}
//apolloClient.js

import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
    uri: 'https://countries.trevorblades.com/graphql',
    cache: new InMemoryCache()
});

export default client;
//App.js

import './App.css';
import { gql, useQuery } from '@apollo/client';

const GET_COUNTRY = gql`
  query {
    country(code: "BR") {
      name
      currency
    }
  }
`;

function App() {
    const { loading, error, data } = useQuery(GET_COUNTRY);

    return (
        <div className="App">
            <header className="App-header">
                {loading && <p>Loading...</p>}
                {error && <p>Error: {error.message}</p>}
                {data && (
                    <p>
                        {data.country.name} - {data.country.currency}
                    </p>
                )}
            </header>
        </div>
    );
}

export default App;
// index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { ApolloProvider } from '@apollo/client';
import client from './apolloClient';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <ApolloProvider client={client}>
            <App />
        </ApolloProvider>
    </React.StrictMode>
);

Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output: Your project will be shown in the URL http://localhost:3000/

qws

Conclusion:

In this article, we learned about GraphQL queries, and how they can be useful in querying and fetching just the data that the client wants from the server. We also learnt about how we can fetch the data and execute the GraphQL queries in react using the "useQuery" hook, and how we can display the fetched data in the UI.

Article Tags :