Skip to main content

GraphQL is a query language for APIs and a runtime for executing those queries with your existing data. It provides a more efficient and powerful alternative to REST APIs, allowing clients to request only the data they need. GraphQL is often used with libraries like Apollo Client or Relay to manage data fetching and state management in React applications.

Apollo Client

Apollo Client is a popular GraphQL client that helps you manage data fetching and state management in your React applications. It provides a powerful set of features, including caching, optimistic UI updates, and real-time data updates with subscriptions.

npm install @apollo/client graphql
# or
yarn add @apollo/client graphql

Example

info

Client CORS

Your React client will probably encounter CORS issues when trying to access this GraphQL API. the cors-anywhere service is a simple proxy that allows you to bypass CORS restrictions.

File: src/apollo-client.tsx

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

const client = new ApolloClient({
uri: 'https://cors-anywhere.herokuapp.com/https://graphql-teas-endpoint.netlify.app/',
cache: new InMemoryCache(),
})

export default client

Tea Component

The Tea component fetches a list of teas from the GraphQL API using the Apollo Client. It uses the useQuery hook to execute the GraphQL query and handle loading and error states.

File: src/Teas.tsx

//@ts-nocheck
// Typescript probably doesn't know about the GraphQL types
import { gql, useQuery } from '@apollo/client';

const GET_TEA = gql`
query allTea {
teas {
name
id
}
}
`

const Tea = () => {
const { loading, error, data } = useQuery(GET_TEA);

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

return (
<div className="p-4">
<h2 className="text-xl font-bold mb-2">Users</h2>
<ul className="space-y-2">

{
data.teas.map((tea: any) => {
return(
<li key={tea.id}
className="p-2 bg-gray-100 rounded">
<p><strong>{tea.name}</strong></p>
</li>
)
})
}
</ul>
</div>
)
}

export default Tea

App Component

The App component is the main entry point of the application. It wraps the entire application in an ApolloProvider to provide the Apollo Client instance to all components.

File: src/App.tsx

import { ApolloProvider } from '@apollo/client';
import client from './apolloClient';
import Tea from './Tea';

const App = ()=> {
return (
<ApolloProvider client={client}>
<div className="container mx-auto p-4">
<h1 className="text-2xl font-bold mb-4">Apollo Client + React + Tea</h1>
<Tea />
</div>
</ApolloProvider>
);
}


export default App