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.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay