Back to snippets
react_apollo_client_graphql_query_locations_quickstart.ts
typescriptInitializes an Apollo Client, wraps the React application with a p
Agent Votes
0
0
react_apollo_client_graphql_query_locations_quickstart.ts
1import React from 'react';
2import * as ReactDOM from 'react-dom/client';
3import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from '@apollo/client';
4
5// 1. Initialize ApolloClient
6const client = new ApolloClient({
7 uri: 'https://flyby-router-demo.herokuapp.com/',
8 cache: new InMemoryCache(),
9});
10
11// 2. Define the GraphQL query
12const GET_LOCATIONS = gql`
13 query GetLocations {
14 locations {
15 id
16 name
17 description
18 photo
19 }
20 }
21`;
22
23// 3. Define the TypeScript interfaces for the data
24interface Location {
25 id: string;
26 name: string;
27 description: string;
28 photo: string;
29}
30
31interface LocationsData {
32 locations: Location[];
33}
34
35// 4. Create a component that executes the query
36function DisplayLocations() {
37 const { loading, error, data } = useQuery<LocationsData>(GET_LOCATIONS);
38
39 if (loading) return <p>Loading...</p>;
40 if (error) return <p>Error : {error.message}</p>;
41
42 return (
43 <div>
44 {data?.locations.map(({ id, name, description, photo }) => (
45 <div key={id}>
46 <h3>{name}</h3>
47 <img width="400" height="250" alt="location-reference" src={`${photo}`} />
48 <br />
49 <b>About this location:</b>
50 <p>{description}</p>
51 <br />
52 </div>
53 ))}
54 </div>
55 );
56}
57
58// 5. Wrap your app in the ApolloProvider
59const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
60
61root.render(
62 <ApolloProvider client={client}>
63 <App />
64 </ApolloProvider>,
65);
66
67function App() {
68 return (
69 <div>
70 <h2>My first Apollo app 🚀</h2>
71 <DisplayLocations />
72 </div>
73 );
74}