Getting Started With Apollo Client in Your React App

What is Apollo Client?

Apollo Client Architecture Diagram by Adhithi Ravichandran

Integrate Apollo Client

Installation

Imports

import {
ApolloClient,
InMemoryCache,
ApolloProvider,
useQuery,
gql
} from "@apollo/client";

Create Apollo Client

const client = new ApolloClient({
uri: ”https://my-example-url.com”, // Your running GraphQL server URL
cache: new InMemoryCache()
});

Connect Apollo Client to React with Apollo Provider

<ApolloProvider client = {client}>
<App />
</ApolloProvider>

Consume GraphQL API and Execute Queries

useQuery Hook

const ALL_SESSIONS = gql`
query sessions {
sessions {
id
title
startsAt
day
room
level
speakers {
id
name
}
}
}`;
const { loading, error, data } = useQuery(ALL_SESSIONS);
function AllSessionList() {
const { loading, error, data } = useQuery(ALL_SESSIONS);
if (loading) return <p>Loading Sessions..</p>; if (error) return <p>Error loading sessions!</p>; return data.sessions.map((session) => (
<SessionItem
key={session.id}
session={{
...session,
}}
/>
));
}

Arguments in Queries

const WEDNESDAY_SESSIONS = gql`
query sessions {
sessions(day:"Wednesday") {
id
title
startsAt
day
room
level
speakers {
id
name
}
}
}`;

Variables in Queries

const SESSIONS = gql`
query sessions($day: String!) {
sessions(day: $day) {
id
title
startsAt
day
room
level
speakers {
id
name
}
}
}`;
const { loading, error, data } = useQuery(SESSIONS, {
variables: { day },
});

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adhithi Ravichandran

Software Consultant, Author, Speaker, React Native|React|GraphQL|Cypress Dev & Indian Classical Musician