-
Install
create-react-app
if you haven't already done so. Use it to build out a new React app. Start the local server as instructed. -
Install the following npm packages:
npm install @apollo/client graphql
Documentation:
-
Import
apollo-client
and instantiate it, pointing it at your local GraphQL server:import { ApolloClient, InMemoryCache, ApolloProvider, gql } from '@apollo/client'; const client = new ApolloClient({ uri: 'http://localhost:4001/graphql', cache: new InMemoryCache(), });
-
Wrap your
<App>
in anApolloProvider
component:ReactDOM.render( // for React < v18 // alternatively root.render(...) <ApolloProvider client={client}> <App /> </ApolloProvider>, document.getElementById('root') // for React < v18 );
-
Import the Apollo client libraries:
import { useQuery, gql } from '@apollo/client';
-
Add your query. For example, let's make a "hello" query:
const GET_HELLO_WORLD = gql` query GetHelloWorld { system { hello } } `;
-
Now we just need to render the data received. I recommend installing the React DevTools if you haven't already done so, to view the component's props so you can see the data returned by the server. I added a paragraph to my
App
render function as follows:function App() { const { loading, error, data } = useQuery(GET_HELLO_WORLD); return ( <div className="App"> <header className="App-header"> {loading && <p>Loading...</p>} {error && <p>An error occurred</p>} <p>{data?.system?.hello}</p> </header> </div> ); }
- The Apollo team has taken the approach of enabling you to simply copy a query from GraphiQL and paste it into your code. What do you think of Apollo's approach?
- If a component has a tree of nested children, how could the GraphQL response data be propagated down them?
Next steps to take are:
- Investigate
this.props.data.loading
, and implement a "Loading…" spinner. - Refactor the code into a
System
component. What props might this component receive?