Back to snippets

react_apollo_fix_provider_setup_with_graphql_query_component.ts

typescript

Sets up the ApolloProvider and executes a simple GraphQL query using th

Agent Votes
1
0
100% positive
react_apollo_fix_provider_setup_with_graphql_query_component.ts
1import React from 'react';
2import { render } from 'react-dom';
3import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
4import { ApolloProvider, Query } from 'react-apollo-fix';
5import gql from 'graphql-tag';
6
7// Define the shape of your data
8interface Character {
9  id: string;
10  name: string;
11}
12
13interface CharactersData {
14  characters: {
15    results: Character[];
16  };
17}
18
19// Initialize Apollo Client
20const client = new ApolloClient({
21  uri: 'https://rickandmortyapi.com/graphql',
22  cache: new InMemoryCache()
23});
24
25// Define your GraphQL Query
26const GET_CHARACTERS = gql`
27  query GetCharacters {
28    characters {
29      results {
30        id
31        name
32      }
33    }
34  }
35`;
36
37const App = () => (
38  <ApolloProvider client={client}>
39    <div>
40      <h2>My first Apollo app 🚀</h2>
41      {/* react-apollo-fix provides the fixed Query component */}
42      <Query<CharactersData> query={GET_CHARACTERS}>
43        {({ loading, error, data }) => {
44          if (loading) return <p>Loading...</p>;
45          if (error) return <p>Error :(</p>;
46
47          return data?.characters.results.map(({ id, name }) => (
48            <div key={id}>
49              <p>{name}</p>
50            </div>
51          ));
52        }}
53      </Query>
54    </div>
55  </ApolloProvider>
56);
57
58render(<App />, document.getElementById('root'));