DEV Community

Cover image for Integrating Apollo Client with React and TypeScript: A Step-by-Step Guide
Mourya Vamsi Modugula
Mourya Vamsi Modugula

Posted on

Integrating Apollo Client with React and TypeScript: A Step-by-Step Guide

To load Apollo GraphQL in a React TypeScript (TSX) application, you can follow these detailed steps:

1. Set Up a New React Application (if not already)

If you don’t have a React TypeScript project, you can create one using:

   npx create-react-app your-app-name --template typescript
   cd your-app-name
Enter fullscreen mode Exit fullscreen mode

2. Install Apollo Client and GraphQL

Install the necessary Apollo Client packages and GraphQL:

   yarn add @apollo/client graphql
Enter fullscreen mode Exit fullscreen mode

This command installs the Apollo Client library and graphql, which is required to parse GraphQL queries.

3. Set Up Apollo Client

In your project’s source folder, create a file called apolloClient.ts to set up Apollo Client.

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

   const client = new ApolloClient({
     uri: 'https://your-graphql-endpoint.com/graphql',  // Replace with your GraphQL API endpoint
     cache: new InMemoryCache(),  // InMemoryCache is useful for caching queries
   });

   export default client;
Enter fullscreen mode Exit fullscreen mode
  • uri: This is where you’ll specify your GraphQL server endpoint.
  • InMemoryCache: Apollo uses this to cache query results.

4. Wrap Your Application with ApolloProvider

Now, you need to wrap your React application with the ApolloProvider, which makes the client accessible throughout your component tree.

In src/index.tsx:

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

   ReactDOM.render(
     <ApolloProvider client={client}>
       <React.StrictMode>
         <App />
       </React.StrictMode>
     </ApolloProvider>,
     document.getElementById('root')
   );
Enter fullscreen mode Exit fullscreen mode

5. Write Your GraphQL Queries or Mutations

In a separate file, define your GraphQL queries or mutations. For example, to fetch data:

   import { gql } from '@apollo/client';

   export const GET_DATA = gql`
     query GetData {
       data {
         id
         name
         description
       }
     }
   `;
Enter fullscreen mode Exit fullscreen mode
  • gql: A tag function to parse GraphQL queries. You can define your queries or mutations here.

6. Using useQuery Hook to Fetch Data

In your component, you can now use Apollo's useQuery hook to fetch data.

   import React from 'react';
   import { useQuery } from '@apollo/client';
   import { GET_DATA } from './queries';

   const DataComponent: React.FC = () => {
     const { loading, error, data } = useQuery(GET_DATA);

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

     return (
       <div>
         {data.data.map((item: { id: string; name: string; description: string }) => (
           <div key={item.id}>
             <h2>{item.name}</h2>
             <p>{item.description}</p>
           </div>
         ))}
       </div>
     );
   };

   export default DataComponent;
Enter fullscreen mode Exit fullscreen mode
  • useQuery: Fetches the data and provides states such as loading, error, and the actual data.
  • Once data is loaded, map through it and display it as needed.

7. Handling Mutations with useMutation

For mutations, you can use the useMutation hook in a similar way.

   import { gql, useMutation } from '@apollo/client';

   const ADD_ITEM = gql`
     mutation AddItem($name: String!, $description: String!) {
       addItem(name: $name, description: $description) {
         id
         name
         description
       }
     }
   `;

   const AddItemComponent: React.FC = () => {
     const [addItem, { data }] = useMutation(ADD_ITEM);

     const handleAddItem = () => {
       addItem({ variables: { name: 'New Item', description: 'Item description' } });
     };

     return (
       <div>
         <button onClick={handleAddItem}>Add Item</button>
         {data && (
           <div>
             <h2>{data.addItem.name}</h2>
             <p>{data.addItem.description}</p>
           </div>
         )}
       </div>
     );
   };

   export default AddItemComponent;
Enter fullscreen mode Exit fullscreen mode
  • useMutation: Executes a GraphQL mutation when the addItem function is called, allowing you to pass dynamic variables.

8. TypeScript Support

Apollo supports TypeScript out of the box. If you want stronger typing for your data, define your types:

   interface DataType {
     id: string;
     name: string;
     description: string;
   }

   const DataComponent: React.FC = () => {
     const { loading, error, data } = useQuery<{ data: DataType[] }>(GET_DATA);
   };
Enter fullscreen mode Exit fullscreen mode

Here, you are providing the expected data type to useQuery, ensuring TypeScript catches any type mismatches.

9. Conclusion

With these steps, you’ve now integrated Apollo Client into your React TypeScript application. This setup allows you to query and mutate data in a strongly-typed environment, improving development speed and ensuring type safety.

Example Snippet :

import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery } from '@apollo/client';
import React from 'react';

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

const GET_DATA = gql`
  query GetData {
    data {
      id
      name
      description
    }
  }
`;

const DataComponent: React.FC = () => {
  const { loading, error, data } = useQuery(GET_DATA);

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

  return (
    <div>
      {data.data.map((item: { id: string; name: string; description: string }) => (
        <div key={item.id}>
          <h2>{item.name}</h2>
          <p>{item.description}</p>
        </div>
      ))}
    </div>
  );
};

const App = () => (
  <ApolloProvider client={client}>
    <DataComponent />
  </ApolloProvider>
);

export default App;
Enter fullscreen mode Exit fullscreen mode

This covers the full flow of setting up Apollo GraphQL in React TSX, from installation to querying and rendering data.

Top comments (0)