Intention: I am learning Spanish from a Spanish teacher and I cannot read my own notes due to my horrible handwriting. My resolution is to build a full-stack app to store new Spanish vocabulary.
Create client.tsx file to store configuration of apollo-client react
import ApolloClient, InMemoryCache and HttpLink from ‘@apollo/client’
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
Initialize and export an instance of ApolloClient
const uri = 'https://countries-274616.ew.r.appspot.com';
const link = new HttpLink({ uri });
const client = new ApolloClient({
cache: new InMemoryCache(),
link
});
export default client;
Test client instance in client.tsx by executing a GraphQL query
Create a new folder named graphql and add get-languages.tsx in it
graphql/get-languages.tsx defines a GraphQL query that returns countries where official language is English.
graphql/get-languages.tsx
import { gql } from '@apollo/client';
export const GET_LANGUAGES = gql`
query getLanguages {
languages: Language(
filter: { name_in: ["English"] },
orderBy: [name_asc]) {
id: _id
name
nativeName
countries {
id: _id
name
flag {
emoji
}
}
}
}
`;
Verify Apollo client can retrieve the results of GET_LANGUAGES and output to console
In client.tsx
import { GET_LANGUAGES } from './graphql/queries';
client.query({
query: GET_LANGUAGES
}).then(console.log);
Connect Apollo Client to React
Import ApolloProvider component and client instance to App.tsx. The client instance is initialized and exported from client.tsx
Wrap ApolloProvider around top level element in App function