Why GraphQL
In the traditional method of using the RESTful approach, we request specific data points which often leads to over-fetching or can sometimes lead to under-fetching. The GraphQL declarative method (we mention the fields we need from the server) of data fetching significantly improves performance over a REST API. For example, consider a webpage that displays the shelter names of pets in the shelter and we also want to get the name of the pet and its image.
USING REST, the page might need to:
- Get a list of shelters and their corresponding pet_ids from the /API/shelters endpoint
- GET each pet’s details (name, photo URL, etc.) with a separate request to /API/pets/PET_ID
We can obtain the above in a single query to a single endpoint using GraphQL, the code for which might look something like this:
query GetPetsByShelter{
shelter{
name
pets{
name
photoURL
}
}
}
Want to know more why to use GraphQL check out :Why Use GraphQL?
Requirements
Get the following installed on your local machine before we begin to code:
- Node.js (preferably version 12 or higher)
- npm (preferably version 6 and can be higher)
- Any code editor of your choice such as Visual Studio Code.
- React.js: Basic familiarity with React.js and its concepts.
- GraphQL API: Have access to a GraphQL API.
How to Integrate GraphQL APIs Into Your React.js Projects
Imagine a React.js world where you can specify exactly the data you need and it flows effortlessly tailored to your needs, and react can efficiently update the DOM as and when needed. No more under-fetching or over-fetching of data or wrestling with nested JSON structures.
This dream becomes a reality with the use of GraphQL the rising star of API technology. This article aims to help you integrate the GraphQL API with your React project.
Table of Content
- What is GraphQL
- Why GraphQL
- How to Integrate GraphQL APIs into Your React.js Projects
- Step 1: Set Up a React Application
- Step 2: Install Required Packages
- Step 3: Using Apollo, Configure the Apollo Client
- Step 4: Create GraphQL Queries
- Step 5: Fetch Data in React Components
- Step 6: Display Data in Your React App
- Step 7: Run Your Application