Introduction
API Integration allows a React application to communicate with a backend service and work with external data. For example, a React application can fetch products, users, blog posts, or weather information from an API and display it on the page. React does not provide a built-in API client, so developers commonly use browser APIs such as fetch() or libraries such as Axios. In this chapter, we will solve practical questions related to API Integration in React. React js API Integration practice questions with solutions help to understand the concepts.
1. What is API Integration in React?
API Integration means connecting a React application with an API so that it can send or receive data.
For example, a React application may request product data from:
https://example.com/api/products
The API may return JSON data:
[
{
"id": 1,
"name": "Laptop",
"price": 55000
},
{
"id": 2,
"name": "Mobile",
"price": 30000
}
]
React can then use this data to display products in the UI.
2. How do you make an API Request in React?
You can use the browser’s built-in fetch() function to make an API request.
Example:
fetch("https://example.com/api/products")
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
The basic process is:
React Component
↓
API Request
↓
Server
↓
API Response
↓
JSON Data
↓
React UI
In a real React application, the received data is usually stored in state so that the UI can update when the data arrives.
3. How do you use fetch() with useEffect() in React?
When a component needs to fetch data after it appears on the page, useEffect() is commonly used.
Example:
import { useEffect, useState } from "react";
function Products() {
const [products, setProducts] = useState([]);
useEffect(() => {
fetch("https://example.com/api/products")
.then((response) => response.json())
.then((data) => {
setProducts(data);
});
}, []);
return (
<div>
<h1>Products</h1>
{products.map((product) => (
<p key={product.id}>
{product.name}
</p>
))}
</div>
);
}
export default Products;
Here:
useEffect()starts the API request.fetch()sends the request.response.json()converts the response into JavaScript data.setProducts()stores the data in state.- React re-renders the component with the received products.
4. How do you check whether an API Request was successful?
fetch() does not reject its Promise just because the server returned an HTTP error such as 404 or 500.
Therefore, it is useful to check response.ok.
fetch("https://example.com/api/products")
.then((response) => {
if (!response.ok) {
throw new Error("Failed to fetch products");
}
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
response.ok is true when the HTTP status is in the successful range.
This check helps your application handle HTTP errors properly.
5. How do you store API Data in React State?
You can use useState() to store data received from an API.
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://example.com/api/users")
.then((response) => {
if (!response.ok) {
throw new Error("Request failed");
}
return response.json();
})
.then((data) => {
setUsers(data);
})
.catch((error) => {
console.error(error);
});
}, []);
return (
<div>
{users.map((user) => (
<p key={user.id}>
{user.name}
</p>
))}
</div>
);
}
export default Users;
The important part is:
const [users, setUsers] = useState([]);
After the API response:
setUsers(data);
React updates the state and re-renders the UI.
6. How do you use async/await for API Integration?
You can use async/await inside an asynchronous function defined within useEffect().
Example:
import { useEffect, useState } from "react";
function Products() {
const [products, setProducts] = useState([]);
useEffect(() => {
async function fetchProducts() {
const response = await fetch(
"https://example.com/api/products"
);
if (!response.ok) {
throw new Error("Failed to fetch products");
}
const data = await response.json();
setProducts(data);
}
fetchProducts();
}, []);
return (
<div>
{products.map((product) => (
<p key={product.id}>
{product.name}
</p>
))}
</div>
);
}
export default Products;
Using async/await can make asynchronous code easier to read.
It is generally better to define the async function inside the effect rather than making the effect callback itself async, because an effect callback should return either nothing or a cleanup function.
7. How do you send Data to an API using POST?
You can use fetch() with the POST method to send data to an API.
Example:
async function addProduct() {
const product = {
name: "Laptop",
price: 55000
};
const response = await fetch(
"https://example.com/api/products",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(product)
}
);
if (!response.ok) {
throw new Error("Failed to add product");
}
const data = await response.json();
console.log(data);
}
Important parts:
method: "POST"
specifies the HTTP method.
headers: {
"Content-Type": "application/json"
}
indicates that JSON is being sent.
body: JSON.stringify(product)
converts the JavaScript object into JSON text.
8. How do you fetch API Data when a Component Loads?
You can place the API request inside useEffect() with an empty dependency array.
useEffect(() => {
async function loadUsers() {
const response = await fetch(
"https://example.com/api/users"
);
if (!response.ok) {
throw new Error("Failed to load users");
}
const data = await response.json();
setUsers(data);
}
loadUsers();
}, []);
The empty dependency array means the effect does not re-run simply because ordinary state or props change; in the usual lifecycle it runs after the initial mount.
In development with React Strict Mode, you may see an extra setup/cleanup cycle, so API code should be written with that behavior in mind.
9. How do you cancel an API Request in React?
For requests such as fetch(), you can use AbortController to cancel an in-progress request.
Example:
import { useEffect } from "react";
function Products() {
useEffect(() => {
const controller = new AbortController();
async function fetchProducts() {
try {
const response = await fetch(
"https://example.com/api/products",
{
signal: controller.signal
}
);
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
console.log(data);
} catch (error) {
if (error.name !== "AbortError") {
console.error(error);
}
}
}
fetchProducts();
return () => {
controller.abort();
};
}, []);
return <h1>Products</h1>;
}
export default Products;
The cleanup function calls:
controller.abort();
This can be useful when a component is removed or when a newer request makes an older request unnecessary.
10. How do you Build a Practical API Integration Component?
Let’s create a practical component that fetches products and displays them.
import { useEffect, useState } from "react";
function Products() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function fetchProducts() {
try {
setLoading(true);
setError("");
const response = await fetch(
"https://example.com/api/products",
{
signal: controller.signal
}
);
if (!response.ok) {
throw new Error("Failed to fetch products");
}
const data = await response.json();
setProducts(data);
} catch (error) {
if (error.name !== "AbortError") {
setError(error.message);
}
} finally {
setLoading(false);
}
}
fetchProducts();
return () => {
controller.abort();
};
}, []);
if (loading) {
return <h2>Loading products...</h2>;
}
if (error) {
return <h2>Error: {error}</h2>;
}
return (
<div>
<h1>Product List</h1>
{products.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>Price: ₹{product.price}</p>
</div>
))}
</div>
);
}
export default Products;
How this example works
The component maintains three pieces of state:
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
They represent:
products → API data
loading → Request status
error → Error message
The API request is started inside useEffect().
If the request succeeds:
setProducts(data);
stores the received data.
If an error occurs:
setError(error.message);
stores the error message.
The UI then displays:
Loading products...
while the request is running,
or:
Error: ...
when the request fails,
or the product list when the request succeeds.
This is a common basic pattern for API integration in React applications.
Key Takeaways
- API Integration allows React applications to communicate with backend services.
- The browser’s
fetch()API can be used without installing an additional package. useEffect()is commonly used when an API request needs to happen as part of component synchronization.- Store API data in React state when it affects the UI.
- Check
response.okbecause HTTP errors do not automatically makefetch()reject. async/awaitcan make API code easier to read.POSTrequests can send JSON data to an API.AbortControllercan be used to cancel an in-progress fetch request.- Loading and error states make API-driven interfaces easier to use.
- Real applications should also consider authentication, caching, retries, validation, and server-side authorization where appropriate.
FAQs
1. What is API Integration in React?
API Integration means connecting a React application to an API to send or receive data.
2. Which function is commonly used to call an API in React?
The browser’s built-in fetch() function is commonly used.
const response = await fetch("/api/products");
Libraries such as Axios can also be used, but they are not required.
3. Why is useEffect used with API requests?
useEffect() is commonly used when fetching data needs to synchronize the component with an external system such as a network request.
4. How do you store API data in React?
You can use useState().
const [products, setProducts] = useState([]);
After receiving the response:
setProducts(data);
5. What is the purpose of response.json()?
response.json() reads the response body and parses JSON data into a JavaScript value.
Example:
const data = await response.json();
6. How do you handle API errors in React?
You can use try...catch with async/await and also check response.ok.
try {
const response = await fetch("/api/products");
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
} catch (error) {
console.error(error);
}
7. Can React directly connect to a database?
Normally, a React application running in the browser should not connect directly to a database.
A common architecture is:
React
↓
Backend / API
↓
Database
The backend handles database access and exposes appropriate API endpoints to the React application.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
