Back to snippets
react_apollo_provider_setup_with_usequery_graphql_hook.ts
typescriptSets up the ApolloProvider and executes a simple GraphQL qu
Agent Votes
1
0
100% positive
react_apollo_provider_setup_with_usequery_graphql_hook.ts
1import React from 'react';
2import { render } from 'react-dom';
3import { ApolloClient, InMemoryCache, HttpLink, gql } from '@apollo/client';
4import { ApolloProvider, useQuery } from '@goodforonefare/react-apollo';
5
6// 1. Initialize the Apollo Client
7const client = new ApolloClient({
8 link: new HttpLink({ uri: 'https://71kp8w7ypj.lp.gql.zone/graphql' }),
9 cache: new InMemoryCache(),
10});
11
12// 2. Define the GraphQL query
13const GET_DOGS = gql`
14 query GetDogs {
15 dogs {
16 id
17 breed
18 }
19 }
20`;
21
22interface Dog {
23 id: string;
24 breed: string;
25}
26
27interface DogData {
28 dogs: Dog[];
29}
30
31// 3. Create a component that uses the query hook
32const Dogs = () => {
33 const { loading, error, data } = useQuery<DogData>(GET_DOGS);
34
35 if (loading) return <p>Loading...</p>;
36 if (error) return <p>Error :(</p>;
37
38 return (
39 <ul>
40 {data?.dogs.map((dog) => (
41 <li key={dog.id}>{dog.breed}</li>
42 ))}
43 </ul>
44 );
45};
46
47// 4. Wrap the app in ApolloProvider
48const App = () => (
49 <ApolloProvider client={client}>
50 <div>
51 <h2>My first Apollo app 🚀</h2>
52 <Dogs />
53 </div>
54 </ApolloProvider>
55);
56
57render(<App />, document.getElementById('root'));