Apollo is a popular GraphQL client library that allows you to consume a GraphQL API from your client-side application. In this tutorial, we will walk through the steps to implement Apollo GraphQL in a React application.
.jpg)
Prerequisites
To follow this tutorial, you should have the following installed on your system:
- Node.js (v10 or later)
- npm (v6 or later)
- React (v16 or later)
Step 1: Create a new React application
First, we need to create a new React application. Open a terminal window and run the following command:
npx create-react-app apollo-graphql-tutorial
This will create a new React application in a directory called apollo-graphql-tutorial. Change into the new directory by running:
cd apollo-graphql-tutorial
Step 2: Install Apollo and dependencies
Next, we need to install the required dependencies for Apollo. Run the following command in the terminal:
npm install @apollo/client graphql
This will install the @apollo/client library and the graphql library, which are required to use Apollo in our application.
Step 3: Set up a GraphQL server
Before we can consume a GraphQL API using Apollo, we need to set up a GraphQL server to consume. For this tutorial, we will use the SpaceX GraphQL API, which provides information about SpaceX launches and rockets.
To set up a GraphQL server, we will use the json-graphql-server package, which allows us to create a GraphQL API based on a JSON file. Create a new file called launches.json in the root directory of your project, and paste the following data into it:
{ "launches": [ { "flight_number": 1, "mission_name": "FalconSat", "launch_year": "2006", "rocket": { "rocket_name": "Falcon 1" } }, { "flight_number": 2, "mission_name": "DemoSat", "launch_year": "2007", "rocket": { "rocket_name": "Falcon 1" } }, { "flight_number": 3, "mission_name": "Trailblazer", "launch_year": "2008", "rocket": { "rocket_name": "Falcon 1" } } ] }
This data represents the first three SpaceX launches, including the flight number, mission name, launch year, and rocket information.
Next, we need to start a GraphQL server using this data. Create a new file called server.js in the root directory of your project, and paste the following code into it:
const { jsonGraphQLServer } = require('json-graphql-server'); const data = require('./launches.json'); const PORT = 4000; jsonGraphQLServer(data, { port: PORT, endpointURL: '/graphql', graphqlRoot: 'root' }).then(() => { console.log(`GraphQL server running at http://localhost:${PORT}/graphql`); });
This code starts a GraphQL server using the json-graphql-server package, and serves the data from the launches.json file. It also specifies that the server should run on port 4000, and that the GraphQL endpoint should be /graphql.
To start the GraphQL server, run the following command in the terminal:
node server.js
This will start the GraphQL server, and you should see a message in the terminal indicating that the server is running.
Step 4: Set up Apollo client
Now that we have set up our GraphQL server, we can start consuming it using Apollo client in our React application.
Open the src/index.js file in your project, and add the following code at the top of the file:
import { ApolloProvider } from '@apollo/client'; import { ApolloClient, InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: 'http://localhost:4000/graphql', cache: new InMemoryCache() });
This code creates a new instance of the ApolloClient, which connects to our GraphQL server running on http://localhost:4000/graphql. It also specifies that we should use the InMemoryCache to cache data returned from the server.
Next, we need to wrap our React application in the ApolloProvider component, which provides the client to our application. Replace the existing ReactDOM.render call with the following code:
ReactDOM.render( <ApolloProvider client={client}> <App /> </ApolloProvider>, document.getElementById('root') );
This code wraps the App component in the ApolloProvider, which passes the Apollo client to all components in our application.
Step 5: Query data using Apollo
Now that we have set up Apollo client and wrapped our application with the ApolloProvider, we can start querying data from our GraphQL server.
import React from 'react'; import { gql, useQuery } from '@apollo/client'; const LAUNCHES_QUERY = gql` query Launches { launches { flight_number mission_name launch_year rocket { rocket_name } } } `; function Launches() { const { loading, error, data } = useQuery(LAUNCHES_QUERY); if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return ( <div> <h1>SpaceX Launches</h1> {data.launches.map(launch => ( <div key={launch.flight_number}> <h2>{launch.mission_name}</h2> <p>Flight Number: {launch.flight_number}</p> <p>Launch Year: {launch.launch_year}</p> <p>Rocket Name: {launch.rocket.rocket_name}</p> </div> ))} </div> ); } export default Launches;
This code defines a GraphQL query using the gql template literal tag, which specifies that we want to fetch the flight_number, mission_name, launch_year, and rocket_name for all launches. It then uses the useQuery hook from Apollo to fetch the data, and renders a list of launches using the data returned from the server.
Next, update the App.js file to render the Launches component by replacing the existing code with the following:
import React from 'react'; import Launches from './Launches'; function App() { return ( <div> <Launches /> </div> ); } export default App;
This code renders the Launches component in our App component.
Finally, start the React development server by running the following command in the terminal:
npm start
This will start the development server and open the application in your default browser. You should see a list of SpaceX launches fetched from the GraphQL server and displayed in the browser. Congratulations! You have successfully implemented Apollo GraphQL in
0 Comments