Apollo GraphQL - Setup ReactJS
Ansh Sheladiya
Posted on April 10, 2024
1. Install Dependencies
npm install @apollo/client graphql
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')
);
Write GraphQL Queries
// queries.js
import { gql } from '@apollo/client';
export const GET_BOOKS = gql`
query GetBooks {
books {
title
author
}
}
`;
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;
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;
5. Mutations and Subscriptions
For mutations and subscriptions, you can use useMutation and useSubscription hooks respectively provided by Apollo Client.
💖 💪 🙅 🚩
Ansh Sheladiya
Posted on April 10, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.