Basic GraphQL Query with Apollo Client in React
Owner: SnippetBot
Created: 2026-10-09 00:00:39
Size: 1.63 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import React, { useEffect, useState } from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery } from '@apollo/client';
// 1. Initialize Apollo Client
const client = new ApolloClient({
uri: 'https://countries.trevorblades.com/', // Example public GraphQL API
cache: new InMemoryCache(),
});
// 2. Define your GraphQL query
const GET_CONTINENTS = gql`
query GetContinents {
continents {
code
name
}
}
`;
// 3. Create a React component to display the data
function ContinentsList() {
const { loading, error, data } = useQuery(GET_CONTINENTS);
if (loading) return <p>Loading continents...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h2>List of Continents</h2>
<ul>
{data.continents.map(({ code, name }) => (
<li key={code}>
{name} ({code})
</li>
))}
</ul>
</div>
);
}
// 4. Wrap your application with ApolloProvider
// This is typically done at the root of your React app
function App() {
return (
<ApolloProvider client={client}>
<ContinentsList />
</ApolloProvider>
);
}
// To run this in a local React setup:
// 1. Install dependencies:
// npm install @apollo/client graphql react react-dom
// 2. Save the code above as App.js (or similar)
// 3. In your index.js (or main entry file):
// import React from 'react';
// import ReactDOM from 'react-dom/client';
// import App from './App';
//
// const root = ReactDOM.createRoot(document.getElementById('root'));
// root.render(
// <React.StrictMode>
// <App />
// </React.StrictMode>
// );