Playing Around with Axios for CRUD

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:

npm create vite@latest axios-crud --template react
cd axios-crud
npm install axios

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.

import React, { useState } from 'react';
import axios from 'axios';

const CreatePost = () => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    const post = { title, body };
    try {
      const response = await axios.post('https://jsonplaceholder.typicode.com/posts', post);
      console.log(response.data);
    } catch (error) {
      console.error('There was an error creating the post!', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Title:</label>
        <input
          type="text"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
      </div>
      <div>
        <label>Body:</label>
        <textarea
          value={body}
          onChange={(e) => setBody(e.target.value)}
        />
      </div>
      <button type="submit">Create Post</button>
    </form>
  );
};

export default CreatePost;

2. Read (GET)

Next, we will create a component called PostList to fetch and display a list of posts.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const PostList = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const fetchPosts = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        setPosts(response.data);
      } catch (error) {
        console.error('There was an error fetching the posts!', error);
      }
    };

    fetchPosts();
  }, []);

  return (
    <div>
      <h2>Post List</h2>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default PostList;

3. Update (PUT)

For the Update operation, we will create a component called UpdatePost to update an existing post.

import React, { useState } from 'react';
import axios from 'axios';

const UpdatePost = ({ postId }) => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');

  const handleUpdate = async (e) => {
    e.preventDefault();
    const updatedPost = { title, body };
    try {
      const response = await axios.put(`https://jsonplaceholder.typicode.com/posts/${postId}`, updatedPost);
      console.log(response.data);
    } catch (error) {
      console.error('There was an error updating the post!', error);
    }
  };

  return (
    <form onSubmit={handleUpdate}>
      <div>
        <label>Title:</label>
        <input
          type="text"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
      </div>
      <div>
        <label>Body:</label>
        <textarea
          value={body}
          onChange={(e) => setBody(e.target.value)}
        />
      </div>
      <button type="submit">Update Post</button>
    </form>
  );
};

export default UpdatePost;

4. Delete (DELETE)

Lastly, we will create a component called DeletePost to delete an existing post.

import React from 'react';
import axios from 'axios';

const DeletePost = ({ postId }) => {
  const handleDelete = async () => {
    try {
      await axios.delete(`https://jsonplaceholder.typicode.com/posts/${postId}`);
      console.log('Post deleted');
    } catch (error) {
      console.error('There was an error deleting the post!', error);
    }
  };

  return (
    <button onClick={handleDelete}>Delete Post</button>
  );
};

export default DeletePost;

Bringing It All Together

To see everything in action, we will create a main component called App that includes all the CRUD operations.

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;

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.

Last updated