Fetch and display data from API in React js
All modern browsers come with an inbuilt fetch Web API, which can be used to fetch data from APIs.
import React, { useEffect, useState } from "react"
const UsingFetch = () => {
const [users, setUsers] = useState([])
const fetchData = () => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => {
return response.json()
})
.then(data => {
setUsers(data)
})
}
useEffect(() => {
fetchData()
}, [])
return (
<div>
{users.length > 0 && (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)}
</div>
)
}
export default UsingFetch
There are many ways to fetch data using React
- Use the JavaScript Fetch() method
- Use the stale-while-revalidate (SWR) method
- Use the React Query library
- Use the Axios Library
- Use the useFetch custom hook from react-fetch-hook
with in this post will try the fetch() method, creating example that work and integrate with Drupal 10
What is an API?
API stands for Application Programming Interface.
It enables the exchange of information and functionality between different systems, such as between a website and a server or between different software applications.
You can think of an API as being like a restaurant waiter.
You don't go inside the kitchen to prepare your meal when you dine at a restaurant. Rather, you inform the waiter of your preferences, and they will take your order to the kitchen team.
The kitchen team prepares the food and returns it to the waiter, who then delivers it to your table.
An API functions as a waiter for software applications.
It is a set of rules that lets one program ask another for something it needs.
It serves as a bridge for software apps to communicate and interact.
What is a Hypertext Transfer Protocol (HTTP) request?
When a web browser or a mobile app sends a message to a server, it's known as an HTTP request.
A HTTP request involves asking the server for specific data or an action and getting a response.
The server responds by interacting with web pages and services.
Using APIs in software development makes things more flexible and efficient.
It also enhances security and enables different software systems to work well together.
Types of HTTP Requests
We use various HTTP request methods, such as get, post, put, and delete, to get and store data in our database.
But the most common requests made are the get and post requests.
Let's discuss the meaning of these HTTP request methods:
GET: This method retrieves data from a specific endpoint.
Think of it as asking for information.
POST: This method sends data to a specific endpoint.
For example, you can send a message or submit a form.
The information will be added to the database.
PUT: This method is used to update a record or data value at a designated endpoint.
You're making changes to existing information.
DELETE: This method erases data from a specific endpoint.
It's like discarding unnecessary things.
Code Snippet
import React, { useEffect, useState } from "react";
function handleClick() {
alert('You clicked node ');
}
export default function RWTaskIssues({nodeid}) {
const FetchAPI = '/rwtask/issues?task=' + nodeid + '&op=get';
console.log("api fetch: " + FetchAPI);
const [issues, setIssues] = useState([]);
const fetchData = () => {
fetch(FetchAPI)
.then(response => {
return response.json();
})
.then(response => {
console.log("response data: " + response.data.items);
setIssues(response.data.items);
});
};
useEffect( () => {
fetchData();
}, []) ;
console.log("issues data: " + issues);
return (
<div className="block block-layout-builder block-field-blocknoderwtaskfield-rwtask-issue">
<h2 className="block-title">תיאור הבעיה</h2>
<div className="block-content">
{issues.length > 0 && (
<div className="field field-name-field-rwtask-issue field-type-text-long field-label-hidden field-items">
{issues.map(item => (
<div key={item.key} className="field-item" dangerouslySetInnerHTML={{__html: item.value}} />
) ) }
</div>
)}
<button onClick={handleClick}>
Edit
</button>
</div>
</div>
);
}