DEV Community

Ansh Sheladiya
Ansh Sheladiya

Posted on

Apollo GraphQL - Setup ReactJS

1. Install Dependencies

npm install @apollo/client graphql

Enter fullscreen mode Exit fullscreen mode

Configure Apollo Client

// index.js or App.js

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

const client = new ApolloClient({
  uri: 'YOUR_GRAPHQL_ENDPOINT_URI',
  cache: new InMemoryCache()
});

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('root')
);

Enter fullscreen mode Exit fullscreen mode

Write GraphQL Queries

// queries.js

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

export const GET_BOOKS = gql`
  query GetBooks {
    books {
      title
      author
    }
  }
`;

Enter fullscreen mode Exit fullscreen mode

4. Use Query Component or Hooks
Using useQuery hook:

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

const BookList = () => {
  const { loading, error, data } = useQuery(GET_BOOKS);

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

  return (
    <div>
      {data.books.map((book, index) => (
        <div key={index}>
          <h3>{book.title}</h3>
          <p>{book.author}</p>
        </div>
      ))}
    </div>
  );
};

export default BookList;

Enter fullscreen mode Exit fullscreen mode

Using Query component:

import React from 'react';
import { Query } from '@apollo/client/react/components';
import { GET_BOOKS } from './queries';

const BookList = () => (
  <Query query={GET_BOOKS}>
    {({ loading, error, data }) => {
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error :(</p>;

      return (
        <div>
          {data.books.map((book, index) => (
            <div key={index}>
              <h3>{book.title}</h3>
              <p>{book.author}</p>
            </div>
          ))}
        </div>
      );
    }}
  </Query>
);

export default BookList;

Enter fullscreen mode Exit fullscreen mode

5. Mutations and Subscriptions

For mutations and subscriptions, you can use useMutation and useSubscription hooks respectively provided by Apollo Client.

Top comments (0)