- read

Integrating GraphQL in React.js: Simplifying Data Fetching

Jayanth babu 65

Integrating GraphQL in React.js: Simplifying Data Fetching

Jayanth babu
Level Up Coding
Published in
5 min read6 days ago

--

In the evolving landscape of web development, efficiently managing and retrieving data remains a pivotal challenge. Traditional REST APIs, commonly used in React.js applications, often lead to either over-fetching or under-fetching of data. This not only impacts performance but also complicates the data management process. Enter GraphQL, a modern alternative that revolutionizes this interaction by enabling precise and efficient data retrieval. Unlike REST, GraphQL allows clients to specify exactly what data they need, leading to more efficient network requests.

In this blog, we’ll walk through the steps to integrate a GraphQL API with a React.js application using Apollo Client.

What is GraphQL?

GraphQL is a query language for your API, and a server-side runtime for executing those queries by parsing your data. It isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.

To integrate GraphQL into a React.js application, we will use Apollo Client, a popular, feature-rich GraphQL client that provides a comprehensive approach to data management in modern web applications.

Setting Up Apollo Client

To integrate Apollo Client into your React app, you’ll first need to install it:

npm install @apollo/client graphql

Next, you’ll need to set up ApolloClient and the ApolloProvider. This provider component uses React’s Context API to make a client instance available throughout the component tree.

For demonstration, we’ll use the SpaceX GraphQL API, which is a public API that provides data about SpaceX launches.

Here’s how you configure Apollo Client with this real GraphQL endpoint:

import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";
import DashBoard from "./Dashboard";
import LaunchesSearch from "./LaunchesSearch";
// Initialize the ApolloClient instance with the SpaceX GraphQL API endpoint
const client = new ApolloClient({
uri: "https://spacex-production.up.railway.app/",
cache: new InMemoryCache()
});

// ApolloProvider wraps your React app and places the client on the context,
// which allows you to access it from anywhere in your component tree.
const App = () => (
<ApolloProvider client={client}>
<DashBoard />
</ApolloProvider>
);

export default App;

With this configuration, your React application is now ready to query the SpaceX API and render the data in your UI. You can use the provided useQuery, useMutation, and useSubscriptionhooks to interact with the API according to your application's needs.

Fetching Data in the Dashboard Component
Within the Dashboard component, you can now make use of Apollo Client’s useQueryhook to fetch data from the SpaceX API. The useQueryhook leverages React's Hooks API to fetch and load data from GraphQL queries.

Here’s an example of how to use useQuery to retrieve a list of SpaceX launches:

import { useQuery, gql } from "@apollo/client";
import styles from "./Dashboard.module.css";

// Define the GraphQL query
const GET_LAUNCHES = gql`
query GetLaunchList {
launchesPast(limit: 5) {
mission_name
launch_date_local
links {
article_link
video_link
}
}
}
`;

// The Dashboard component
const Dashboard = () => {
const { loading, error, data } = useQuery(GET_LAUNCHES);

if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;

return (
<div>
<h1 className={styles.title}>SpaceX Launches</h1>
<div className={styles.launchesContainer}>
{data.launchesPast.map((launch) => (
<div key={launch.mission_name} className={styles.card}>
<h2>{launch.mission_name}</h2>
<p>
Launch Date:{" "}
{new Date(launch.launch_date_local).toLocaleDateString("en-US")}
</p>
</div>
))}
</div>
</div>
);
};

export default Dashboard;

In this code, we are creating a simple UI that maps over the array of past launches returned by the GET_LAUNCHESquery. Each launch is displayed in its own div with details such as mission name, launch date.

Advanced Data Fetching Techniques with Apollo Client

As you become more comfortable with the basics of fetching data using Apollo Client, you’ll soon run into scenarios that require more advanced techniques. Let’s delve into some of these techniques to enhance your React applications.

Using variables in your GraphQL queries allows you to write dynamic and reusable queries that can adapt based on user interaction or component state changes. Let’s walk through an example where users can filter a list of launches by a mission name that they input into a search field.

First, we define our GraphQL query to accept a variable for the mission name:

// Define the GraphQL query with a variable
const GET_LAUNCHES_BY_MISSION_NAME = gql`
query GetLaunchesByMissionName($missionName: String!) {
launchesPast(find: { mission_name: $missionName }) {
mission_name
launch_date_local
}
}
`;

Next, we’ll create a React component with a search field where users can type in a mission name. We'll use Apollo Client's useQueryhook to fetch the launches based on the mission nameprovided.

Here’s a concise example of how that might look in your React component:

const LaunchesSearch = () => {
const [missionName, setMissionName] = useState("");
const { data, loading, error } = useQuery(GET_LAUNCHES_BY_MISSION_NAME, {
variables: { missionName },
skip: !missionName // Skip the query if no mission name is entered
});

if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;

return (
<div>
<input
type="text"
placeholder="Enter Mission Name"
value={missionName}
onChange={(e) => setMissionName(e.target.value)}
/>
{data && (
<ul>
{data.launchesPast.map((launch) => (
<li key={launch.mission_name}>
<strong>{launch.mission_name}</strong> -{" "}
{new Date(launch.launch_date_local).toLocaleDateString()}
</li>
))}
</ul>
)}
</div>
);
};

export default LaunchesSearch;

n the LaunchesSearchcomponent, we are maintaining the state for missionNamewhich is updated whenever the input field changes. The useQueryhook then uses this state as a variable for the GraphQL query, which will refetch the data whenever the missionNamechanges. The skip option is used to avoid executing the query before the user has entered a search term.

This pattern is highly effective for creating interactive and responsive interfaces that provide feedback to the user as they search or filter data.

The complete working code example you can found here.

Conclusion

We’ve seen how to integrate a GraphQL API into a React.js application using Apollo Client, from setting up Apollo Client and configuring it to use a real GraphQL endpoint, to fetching data and displaying it with a styled component. GraphQL’s power lies in its ability to allow clients to request exactly what they need, and Apollo Client makes it easy to fetch, cache, and manage that data in a React.js application.

Remember, the SpaceX API used in this example is a real public API, which makes it an excellent resource for practicing GraphQL queries and mutations.

Integrating GraphQL with React.js can significantly improve the performance and user experience of your application by avoiding over-fetching or under-fetching of data. With tools like Apollo Client, it becomes relatively straightforward to manage your data and keep your UI in sync with the state of your data in the backend.

I hope this guide has been helpful to get you started with GraphQL in React.js applications. With the basic setup done, you’re now ready to explore more advanced features of Apollo Client such as local state management, error handling, and subscriptions for real-time updates.

Happy coding!