In this post, we will discuss How to make an API fetch request on the button click Reactjs?. I’m assuming that you are clear about React Js from and about the React Js framework and you are also familiar with creating React Js applications. if you are not clear about these then please read the below post.
we will create a web page with textbox and HTML table list.we are binding the table with the data list returned by API.we want to filter the user list by user city so when we click the search button, we pass one parameter into a fetch API request.
In this post we will cover the following points:
Step 1 – Create React App
Step 2 – Create components for showing List data
Step 3 – Integrate Rest API and handle button click event
import React, { useState, useEffect } from "react";
const FetchDataOnButton = () => {
const [userList, setusers] = useState(null);
const [searchtxt, setSearch] = useState("")
useEffect(() => {
getuesers("http://samplerestapi.com/api/Metadata/users");
}, []);
const getuesers = (url) => {
fetch(url)
.then((res) => res.json())
.then(
(result) => {
setusers(result);
},
(error) => {
console.log(error)
setusers(null);
}
);
};
const handleValue = e => {
setSearch(e.target.value)
}
const searchUser = e => {
e.preventDefault()
getuesers("http://samplerestapi.com/api/Metadata/GetUsersByParam?city="+searchtxt);
}
if (!userList) return <div>No Record Found</div>;
return (
<div>
<h2>Users List Funcational Component </h2>
<div className="row">
<div className="col-sm-6">
<input
type='text'
name='city'
className="form-control"
value={searchtxt}
placeholder='city'
onChange={e => handleValue(e)}
/>
</div>
<div className="col-sm-6">
<input
className='btn btn-primary btnsubmit'
type='submit'
value='Search'
onClick={searchUser}
/>
</div>
</div>
<table className="table">
<thead>
<tr>
<th>User Id</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>ZipCode</th>
</tr>
</thead>
<tbody>
{userList.map((user) => (
<tr>
<td>{user.Id}</td>
<td>{user.Name}</td>
<td>{user.Address}</td>
<td>{user.City}</td>
<td>{user.ZipCode}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default FetchDataOnButton;
So on the button is clicked, we are making an HTTP request, Updating the state variables, and rendering the data.
Functional Component:The FetchDataOnButton component is defined as an arrow function.
Two state variables are declared using the useState hook: userList to store the list of users fetched from the API, and searchtxt to store the text input for city search.
The useEffect hook is utilized to perform side effects in the component. It's used here to fetch the list of users from a specified API endpoint (http://samplerestapi.com/api/Metadata/users) when the component mounts. The getusers function is called inside the useEffect hook.
Fetch Data Function: This function takes a URL parameter and makes a GET request to the specified URL. Upon receiving a response, it converts the response to JSON format and updates the userList state with the fetched data. If there's an error during the request, it logs the error and sets userList to null.
Input Change Handler: The handleValue function updates the searchtxt state with the value entered in the input field for city search.
Search User Function: The searchUser function is triggered when the search button is clicked. It prevents the default form submission behavior, then calls the getusers function with a modified URL based on the searchtxt state, fetching users filtered by city.
Conditional Rendering: If userList is null, it renders a message saying "No Record Found". This handles cases where data hasn't been fetched yet or if there's an error fetching the data.Otherwise, it renders a table displaying the list of users. Each user's details such as id, name, address, city, and zip code are displayed in separate table cells.
It fetches a list of users from an API based on a city search input. It updates the user interface dynamically based on user interaction with the search input and button.
We will discuss this in the next article, but make a note of the two-component types stateless functional components and stateful class components. Now that we have some understanding of the React components, let’s understand the App component in our Hello World react application
it is a JavaScript file. The class is named App and extends the component class from the React library, it contains a render method that returns some HTML.
You can have thousands of components. Facebook, I believe, has over 30000 components, is more complex, and the application has more a number of components. All right, then let me quickly summarize what we have learned about components