In React, we have already seen the API request handling in a class component. The class component is the old approach in React JS. After releasing React 16.8, we are accustomed to the functional component. The functional component helps in writing a more cleaned-up code than the class component. In React posts, I have already shared tutorials on CRUD and Todo App using the class component. Also, in our last post on React, we have seen the use of React hook. Now, it’s time to group the functional component and react hook to handle the API request. For API request handling, we will use the Axios library. To manage the state, we will use the React useState hook. Also, instead of life cycle methods, we will use the useEffect hook.
Prerequisites
I am assuming you are familiar with the basic concepts of React as mentioned below-
- React Basics
- Class and function component in React
- State in class component
- Life cycle methods
For the development environment, you must have the Node installed in your system.
Before creating any app, let’s understand what we will create here. We will be handling the API request using the Axios library. Here, for the API, we will use the dummy API using the JSON placeholder. In the HTTP request method, we will use the GET, POST, PUT and DELETE requests.
So, let’s start by creating a new app in React.
Create React App For API Handling Using React Hook
To create a new app in React, just open the terminal or command prompt and hit the below command.
npx create-react-app myblog
Here, the installation is started. It will take a couple of minutes to finish the installation.
Once the app is created, let’s navigate to the app folder. Now, run it using the below command.
cd myblog
npm start
It will redirect you to the browser automatically.
How to Create Loading Spinner Using Bootstrap in React JS
Install Axios in React For API Handling
For API request handling, we will use the Axios library. This library will need to be installed inside the app. For installing this library, hit the below command in the terminal inside the app.
npm install axios
Here, the Axios library is installed in our app.
In the next step, I will be installing the Bootstrap.
Install Bootstrap in React
For UI designing, we will be using Bootstrap. So, here, I am installing the latest version of Bootstrap (5.1.1).
npm i bootstrap
Now, our application is ready to create component and API handling. But, one more important functionality is still there. That is the component linking through the route. We’ll have more than one component. So, in order to interlink the components through the URL, you will need the router.
File Upload in React JS Using Laravel 8 RESTful API
Install React Router DOM
All the routes will be managed by this library. Hence, inside the terminal, just hit the below command.
npm i react-router-dom
Now, you are good to go for creating the blog app.
Create Components in React JS
In this post, I will show you the basic demo of API handling in React functional component. Therefore, I will create a basic blog app using the demo (fake) API for the demo purpose. However, by end of this post, you will have the brief concept of API handling using the hook in React.
Initially, create a folder named components inside the src folder. After that create another folder inside the components folder named posts. Actually, it is a good practice to have a structured way of your file. Hence, your directory should look like this –
src | --> components | --> posts
Now, inside the posts folder, we will create the following components-
- CreatePost.jsx – This component will contain the form to create and edit post.
- Main.jsx – In this component, we will list out the posts in the table format.
- ViewPost.jsx – This will have the readonly fields to view the post.
- index.js – All the components will be exported from this index.js file. This is just a landing component of all the other components.
- MainRouter.jsx – We will use this component for the route management of the posts.
Now, the final look after creating the components and router is like this –
So, the files are ready. Now, it’s time to put some code on these components. Start with index.js.
Export Components From a Landing Component
The main purpose for creating the index.js is to make a landing point of all the components inside its folder. Hence, we have the posts folder, so, add the below code.
export { CreatePost } from "./CreatePost";
export { ViewPost } from "./ViewPost";
export { PostsMain } from "./Main";
export { PostsRouter } from "./PostsRouter";
However, this landing component (route) is for the posts. So, this will require to import in the App.js. The reason is by default, React has the main landing component as App.js.
Therefore, let’s import it inside the App component as shown below.
import React from "react";
import { PostsRouter } from "./components/posts";
import { BrowserRouter as Router } from "react-router-dom";
import "./App.css";
export const App = () => {
return (
<>
<Router>
<PostsRouter />
</Router>
</>
);
};
export default App;
Form Handling in React JS With Validation Using React State
Posts Listing Using React Hook
For the blog posts API, I will use jsonplaceholder. You may use other sources for the fake API. Even you can create a RESTful API and then integrate it here.
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useLocation, useHistory } from "react-router-dom";
import { Link } from "react-router-dom";
export const PostsMain = () => {
const [posts, setPosts] = useState([]);
const history = useHistory();
useEffect(() => {
getPosts();
}, []);
// get posts
const getPosts = () => {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
if (response.status === 200) {
setPosts(response?.data);
}
})
.catch((error) => {
console.log(error);
});
};
// action click
const actionClick = (data) => {
data.e.stopPropagation();
if (data && data?.action && data?.action?.type === "view") {
history.push(`/posts/view/${data?.post?.id}`);
return false;
} else if (data && data?.action && data?.action?.type === "edit") {
history.push(`/posts/edit/${data?.post?.id}`);
return false;
} else if (data && data?.action && data?.action?.type === "delete") {
deletePost(data?.post?.id);
return false;
}
};
// delete post
const deletePost = (postId) => {
axios
.delete(`https://jsonplaceholder.typicode.com/posts/${postId}`)
.then((response) => {
if (response.status === 200) {
console.log(response);
}
})
.catch((error) => {
console.log(error);
});
};
return (
<div className="container my-4">
<div className="row">
<div className="col-xl-6">
<h4 className="fw-bold">API Handing Using React Hooks</h4>
</div>
<div className="col-xl-6 text-end">
<Link to={`/posts/create`} className="btn btn-sm btn-primary">
Create Post
</Link>
</div>
</div>
<table className="table table-striped my-5">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{posts &&
posts.map((post) => (
<tr
key={post?.id}
onClick={(e) =>
actionClick({ action: { type: "view" }, post, e })
}
>
<td> {post?.id} </td>
<td> {post?.title} </td>
<td> {post?.body} </td>
<td>
<Link
to={"#"}
onClick={(e) =>
actionClick({ action: { type: "edit" }, post, e })
}
title={"Edit"}
>
Edit
</Link>
<Link
to={"#"}
className="ms-3"
onClick={(e) =>
actionClick({ action: { type: "delete" }, post, e })
}
title={"Delete"}
>
Delete
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
In the above code, I have used useEffect, and useState React hook. I already shared a post on the React hook. The useEffect hook is used here as the component life cycle method.
To check the result, open the browser with the posts route as shown below.
When you will click on Create Post, it will open the CreatePost component.
Brief Overview of React Routing Using React Router DOM
Create Post With React Hook
For creating the post, you will need a form with two inputs-
- title and
- body
The same component will be used for updating the post too. To manage the input control, we used React useState hook. The form inputs value is set in the state using React Hook. Hence, check the result in the browser.
import React, { useEffect, useState } from "react";
import axios from "axios";
import { useHistory } from "react-router-dom";
export const CreatePost = ({ isEdit, match }) => {
const [post, setPost] = useState([]);
const history = useHistory();
useEffect(() => {
getPost();
}, [match?.params?.id]);
const formSubmit = (event) => {
event.preventDefault();
const createResult = !isEdit && createPost();
createResult && console.log("Success! post created");
const updateResult = isEdit && updatePost();
updateResult && console.log("Success! post updated");
};
// fetch post
const getPost = () => {
axios
.get(`https://jsonplaceholder.typicode.com/posts/${match?.params?.id}`)
.then((response) => {
if (response.status === 200) {
setPost(() => response?.data);
}
})
.catch((error) => {
console.log(error);
});
};
// create post
const createPost = () => {
axios
.post("https://jsonplaceholder.typicode.com/posts", {
title: post?.title,
body: post?.body,
})
.then((response) => {
response &&
response?.status === 200 &&
history.push(`/posts/view/${match?.params?.id}`);
})
.catch((error) => {
console.log(error);
});
};
// update post
const updatePost = () => {
axios
.put(`https://jsonplaceholder.typicode.com/posts/${match?.params?.id}`, {
title: post?.title,
body: post?.body,
})
.then((response) => {
response &&
response?.status === 200 &&
history.push(`/posts/view/${match?.params?.id}`);
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
};
// onchange event
const onChange = (e) => {
setPost({
...post,
[e.target.name]: e.target.value,
});
};
return (
<div className="container my-4">
<div className="row">
<div className="col-xl-6 m-auto">
<form method={"POST"} onSubmit={(e) => formSubmit(e)}>
<div className="card">
<div className="card-header">
<h5 className="card-title"> {!isEdit && 'Create Post' || 'Update Post'} </h5>
</div>
<div className="card-body">
<div className="form-group">
<label> Title </label>
<input
type="text"
className="form-control"
placeholder="Title"
name="title"
onChange={(e) => onChange(e)}
value={post?.title}
/>
</div>
<div className="form-group my-3">
<label> Description </label>
<textarea
className="form-control"
onChange={(e) => onChange(e)}
placeholder="Description"
name="body"
rows="6"
value={post?.body}
></textarea>
</div>
</div>
<div className="card-footer">
<button type="submit" className="btn btn-success">
{(isEdit && "Update") || "Save"}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
);
};
Here, I haven’t handled the validation for this form. I already shared the post on the form handling with validation.
On submit, it will call the formSubmit function, defined inside the above component.
Create a Todo App in React Using Laravel 8 RESTful APIs
View Post
When you will click on the row of the table inside the Posts listing, it will check the action type. We already passed the action type inside the actionClick() function. As per the action, it will redirect to the route respectively.
In the ViewPost component, there are two more buttons as you can see in the above result. On clicking of Edit button, it will redirect to the CreatePost component in edit mode. Let’s check that.
Edit Post
When a post is opened in the edit mode, the card title inside the CreatePost is changed to Update Post. Also, the same button (Save) is renamed as Update. After updating the post, it will redirect to the View Post again.
React Login and Registration App Using Laravel 7 API
Delete Post
The functionality of deleting the post is handled inside with the same action click function. When you will click on the delete action, it will hit the deletePost() function. Here, I used the fake API, hence, the post won’t be deleted and updated. It is just for demo purposes.
However, you will see the success response message in the console. You can integrate snackbar component or an alert component for that. But, we will see that in our upcoming post when we will work with Material UI in React.
Final Words
In this demo app, we implemented the API requests handling in React functional component. For API request handling we used the Axios library. The React hooks are used here to manage state, and life cycle methods. By using this way, you can implement it in your React app functional component. This was just for the demonstration purpose of API handling in the React functional component. Hence, I haven’t designed it very well and the validation, response message, delete confirmation is not there. But, we will see all these things in the separate post of the upcoming React series. I hope you will find helpful to this post.
Arun Bhatiya says
This is what exactly I was looking for🙏
Thanks a lot buddy for sharing.,its really easy to understand and implement.