Axios is a popular HTTP client that allows you to make requests to a server in an easy and intuitive way. In this blog, we will explore how to use Axios in a React application to perform CRUD (Create, Read, Update, Delete) operations.
Setting Up Your React App
First, let's set up a new React application. You can use Create React App to get started quickly:
This will create a new React application and install Axios, which we will use to handle our HTTP requests.
Creating the Backend API
For demonstration purposes, we will use a mock API provided by JSONPlaceholder, a free online REST API that you can use for testing and prototyping.
Basic CRUD Operations with Axios
1. Create (POST)
Let's start with the Create operation. We will create a new component called CreatePost where we can add a new post.
importReact,{useState}from'react';importaxiosfrom'axios';constCreatePost=()=>{const[title,setTitle]=useState('');const[body,setBody]=useState('');consthandleSubmit=async(e)=>{e.preventDefault();constpost={title,body};try{constresponse=awaitaxios.post('https://jsonplaceholder.typicode.com/posts',post);console.log(response.data);}catch (error) {console.error('There was an error creating the post!',error);}};return (<formonSubmit={handleSubmit}><div><label>Title:</label><inputtype="text"value={title}onChange={(e) =>setTitle(e.target.value)}/></div><div><label>Body:</label><textareavalue={body}onChange={(e) =>setBody(e.target.value)}/></div><buttontype="submit">Create Post</button></form> );};exportdefaultCreatePost;
2. Read (GET)
Next, we will create a component called PostList to fetch and display a list of posts.
3. Update (PUT)
For the Update operation, we will create a component called UpdatePost to update an existing post.
4. Delete (DELETE)
Lastly, we will create a component called DeletePost to delete an existing post.
Bringing It All Together
To see everything in action, we will create a main component called App that includes all the CRUD operations.
Conclusion
In this blog, we've seen how to use Axios to perform CRUD operations in a React application. By using Axios, you can easily handle HTTP requests and manage data in your React applications. This example uses JSONPlaceholder, but you can replace the API endpoints with your own backend.
import React from 'react';
import CreatePost from './CreatePost';
import PostList from './PostList';
import UpdatePost from './UpdatePost';
import DeletePost from './DeletePost';
const App = () => {
const postId = 1; // This is just for demonstration. In a real app, you would get this dynamically.
return (
<div>
<h1>CRUD Operations with Axios</h1>
<CreatePost />
<PostList />
<UpdatePost postId={postId} />
<DeletePost postId={postId} />
</div>
);
};
export default App;