Consuming a GraphQL API using fetch - React Client
Last Updated :
25 Jul, 2024
In this article, we will learn to develop a React application, which will fetch the data from a public GraphQL API using Fetch. We will use The Movie Database Wrapper ( TMDB ) API to fetch the shows available with name/keyword. You can find the API reference and source code links at the end of this article.
Before moving onto the development part, to initialize a simple react application you can follow the steps mentioned below:
Step 1: Create React application.
npx create-react-app foldername
Step 2: Move into the project folder.
cd foldername
Step 3: Create a components folder and now Project Structure will look like:
Project StructureThis was basically the initial setup we require for our application. Now let us take a look at each of the components individually. Custom components reside in the components folder, with everything put together in the MainComponent.jsx, we will place this component inside App.js, which itself goes under the “root” DOM node, and everything inside this node will be managed by React DOM.
We are going to develop three components:
- Main Component: Responsible for fetch operation and state changes in the application.
- Search Bar: A search bar to get the user input for the show name/keyword.
- ShowInfoCard: A reusable component to display the show information.
Step 4: In the MainComponent.jsx component, we have a state variable, data which will hold the response for the GraphQL API.
const [data, setData] = useState(Object);
To fetch the information, we make a call to the apiEndpoint, but first let us break the GraphQL query apart, in general, to form a query, you must specify fields within fields until those fields resolve to actual data. In this way, you ask for specific fields on objects and get back exactly what you asked for. The structure of any GraphQL query looks like this:
query {
JSON objects to retrieve
}
With our query variable, we are trying to fetch all the shows available, using name/keyword, which is passed as an argument with $term.
MainComponent.jsx (query part)
const apiEndpoint = "https://tmdb.apps.quintero.io/";
const query = `
query FetchData($term: String!){
tv{
search(term:$term){
edges{
node{
id
originalName
}
}
}
}
}
`;
To make the request using Fetch API, we send the GraphQL query and variables as a JSON object to the endpoint. GraphQL endpoint expects the body of the request to be a stringified JSON object that contains query and variables parameters. When the request is complete, the promise is resolved with the response object. This object is basically a generic placeholder for various response formats. response.json() is used to extract the JSON object from the response, it returns a promise, which is again resolved and data is updated.
MainComponent.jsx ( request part )
MainComponent.jsx (request part)
const getData = (term) => {
fetch(apiEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query,
variables: { term }
})
})
.then(res => res.json())
.then((data) => setData(data))
.catch(console.error);
};
So finally our MainComponent.jsx looks like:
MainComponent.jsx
import React, { useState } from "react";
import SearchBar from "./SearchBar";
import ShowInfoCard from "./ShowInfoCard";
function Main() {
const [data, setData] = useState(Object);
const apiEndpoint = "https://tmdb.apps.quintero.io/";
const query = `
query FetchData($term: String!){
tv{
search(term:$term){
edges{
node{
id
originalName
}
}
}
}
}
`;
const getData = (term) => {
fetch(apiEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query,
variables: { term }
})
})
.then(res => res.json())
.then((data) => setData(data))
.catch(console.error);
};
// console.log(data)
return (
<div>
<SearchBar getData={getData} />
{data.data ? data.data.tv.search.edges.map(({ node }) => (
<ShowInfoCard key={node.id} node={node} />
)) : <div></div>
}
</div>
);
}
export default Main;
Step 5: Now, moving on to the SearchBar component, which serves the purpose of receiving the user input for name/keyword. It is a simple component, with an input field of text type, and a button to make the search request. The state variable term is updated holds the input from user, and is passed as an argument to getData() when the user makes the search request.
SearchBar.jsx
import React, { useState } from "react";
function SearchBar({getData}){
const [term, setTerm] = useState("");
const onChange = (e) =>{
setTerm(e.target.value)
}
const onSearch = () =>{
getData(term)
}
return(
<div className="searchbar">
<input
placeholder="Enter the name..."
type="text"
value={term}
onChange={(event) => {onChange(event)}}
onKeyUp={(event) => {onChange(event)}}
onPaste={(event) => {onChange(event)}}
/>
<button type="button" className="searchButton"
onClick={onSearch}>Search
</button>
</div>
);
}
export default SearchBar;
Step 6: Our last component, is a reusable UI component, which is basically a Card Component that receives node ( contains the show information ) as props, and just displays it in any chosen format. You can tweak the App.css file to understand the various design aspects.
ShowInfoCard.jsx
import React from "react";
function ShowInfoCard({ node }) {
return (
<div className="datacontainer">
<div className="dataitem">
Name : {node.originalName}
</div>
</div>
);
}
export default ShowInfoCard;
Step 7: Finally, we need to include the MainComponent in App.js file:
App.js
import './App.css';
import React from "react";
import Main from './components/MainComponent';
function App() {
return (
<div className="App">
<header className="App-header">
<h2>Consuming a GraphQL API</h2>
</header>
<Main />
</div>
);
}
export default App;
Step to run the application: To run the application on your system, run the following command:
npm start
Output:
GraphQL API: https://github.com/nerdsupremacist/tmdb
Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Similar Reads
Consuming a REST API ( Github Users ) using Fetch - React Client
In this article, you will learn to develop a React application, which will fetch the data from a REST API using Fetch. We will use GitHub Users API to fetch the user's public information with their username. You can find the API reference and source code links at the end of this article.Prerequisite
2 min read
Create a Community Marketplace App using React
In this article, we will explore the process of developing a Community Marketplace application using React, that offers a seamless and user-friendly experience for users. The Community Marketplace App is a platform where users can buy and sell goods. It provides a convenient way for community member
8 min read
How to Create RESTful API and Fetch Data using ReactJS ?
React JS is more than just an open-source JavaScript library, it's a powerful tool for crafting user interfaces with unparalleled efficiency and clarity. One of React's core principles is its component-based architecture, which aligns perfectly with the Model View Controller (MVC) pattern. React com
5 min read
Consuming a Rest API with Axios in Vue.js
Many times when building an application for the web that you may want to consume and display data from an API in VueJS using JavaScript fetch API, Vue resource, jquery ajax API, but a very popular and most recommended approach is to use Axios, a promise-based HTTP client. Axios is a great HTTP clien
2 min read
Create a Crypto Prediction App using React Native
Crypto Prediction App using React Native allows users to fetch real-time cryptocurrency prices and predict future price movements based on historical data. Users can enter the symbol of the cryptocurrency they're interested in, fetch its current price, and make predictions using simple logic.Output
3 min read
Implementing GraphQL Queries using React Hooks & Apollo Client
Implementing GraphQL queries with React Hooks and Apollo Client involves setting up Apollo Client in your React application, defining GraphQL queries using useQuery hook, and accessing data from the GraphQL API in a declarative way. With Apollo Client, React Hooks like useQuery simplifies the proces
3 min read
Different ways to fetch data using API in React
API: API is an abbreviation for Application Programming Interface which is a collection of communication protocols and subroutines used by various programs to communicate between them. A programmer can make use of various API tools to make its program easier and simpler. Also, an API facilitates pro
4 min read
Create a News Reader app using React-Native
Creating the News Reader application using React-Native language is an exciting project. Using this project, the users can read the news in the application itself, by filtering them according to the categories as per their interest. In this article, we will develop the complete News Reader applicati
5 min read
Using Restify to Create a Simple API in Node.js
Restify is an npm package that is used to create efficient and scalable RESTful APIs in Nodejs. The process of creating APIs using Restify is super simple. Building a RESTful API is a common requirement for many web applications. Restify is a popular Node.js framework that makes it easy to create RE
6 min read
How to fetch data from APIs using Asynchronous await in ReactJS ?
Fetching data from an API in ReactJS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data. PrerequisitesReact JSFetch data from APIApproachTo
3 min read