JAVASCRIPT
Fetch Data from GraphQL API using Apollo Client
Integrate GraphQL APIs into your React application using Apollo Client for efficient data fetching, caching, and state management, leveraging hooks for queries.
// App.js or a component file in a React project
import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery } from '@apollo/client';
// 1. Initialize Apollo Client
const client = new ApolloClient({
uri: 'https://spacex-production.up.railway.app/', // Example GraphQL API endpoint
cache: new InMemoryCache(),
});
// 2. Define your GraphQL query
const GET_LAUNCHES = gql`
query GetLaunches {
launchesPast(limit: 10) {
id
mission_name
launch_date_local
rocket {
rocket_name
}
}
}
`;
// 3. Create a React component to display the data
function LaunchesList() {
const { loading, error, data } = useQuery(GET_LAUNCHES);
if (loading) return <p>Loading launches...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h2>SpaceX Launches (Last 10)</h2>
{data.launchesPast.map(launch => (
<div key={launch.id} style={{ border: '1px solid #ccc', margin: '10px', padding: '10px' }}>
<h3>{launch.mission_name}</h3>
<p>Date: {new Date(launch.launch_date_local).toLocaleDateString()}</p>
<p>Rocket: {launch.rocket.rocket_name}</p>
</div>
))}
</div>
);
}
// 4. Wrap your application with ApolloProvider
function App() {
return (
<ApolloProvider client={client}>
<div style={{ fontFamily: 'sans-serif', margin: '20px' }}>
<h1>GraphQL API Integration Example</h1>
<LaunchesList />
</div>
</ApolloProvider>
);
}
export default App;
// To run this:
// 1. Create a React app: npx create-react-app my-graphql-app
// 2. cd my-graphql-app
// 3. npm install @apollo/client graphql
// 4. Replace src/App.js content with the code above.
// 5. npm start
How it works: This snippet demonstrates how to consume a GraphQL API within a React application using Apollo Client. First, an `ApolloClient` instance is initialized with the GraphQL API URI and an `InMemoryCache`. Next, a GraphQL query is defined using the `gql` tag. The `LaunchesList` component then uses the `useQuery` hook from `@apollo/client` to execute the query, automatically handling loading, error states, and data fetching. Finally, the entire application is wrapped in an `ApolloProvider` to make the client accessible to all child components. This setup provides powerful features like declarative data fetching, caching, and real-time updates for GraphQL APIs.