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