CRUD Operation Using Axios In React

In this article, we will learn about CRUD operations using Axios in react. here Axios allows us to communicate with APIs easily in our react apps.

First, we have to install the Axios npm module in react project like the below code.

npm i axios

Axios give 4 methods which are GET, POST, PUT and DELETE.

here, GET is the method used for fetching data from the API. POST method is used to add new data. The PUT method is used for updating your API data. DELETE method is used for deleting data from API.

How to call API with Axios is given by below code.

App.js

import React, { useEffect, useState } from 'react';
import './App.css';
import Post from './components/post'
function App() {
  return (
    <div style={{ margin: '0px 50px 0px 50px' }}>
      <Post />
    </div>
  );
}
export default App;

Post.js

import React, { useEffect, useState } from 'react'
import { Input, Button, Row, Col } from 'reactstrap'
import DataTable from './dataTable'
import axios from "axios"

export default function Post() {
    const [post, setPost] = useState([])
    const [selectPost, setSelectPost] = useState([])
    const [data, setData] = useState({
        title: "",
        body: ""
    })
    const [msg, setMsg] = useState('')
    useEffect(() => {
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then((response) => {
                setPost(response.data);
            })
    }, [])
    const addPost = () => {
        console.log("data", data)
        const postData = {
            userId: (post.length + 1),
            id: (post.length + 1),
            title: data.title,
            body: data.body
        }
        axios.post('https://jsonplaceholder.typicode.com/posts', postData)
            .then((response) => {
                console.log("successfully add")
                setData({
                    title: "",
                    body: ""
                })
                setMsg("Add successfully")
            }).catch(() => {
                setMsg("error")
            })
    }
    const editPost = () => {
        console.log("data", data)
        const postData = {
            userId: (post.length + 1),
            id: (post.length + 1),
            title: data.title,
            body: data.body
        }
        axios.put(`https://jsonplaceholder.typicode.com/posts/${selectPost.id}`, postData)
            .then((response) => {
                console.log("successfully add")
                setData({
                    title: "",
                    body: ""
                })
                setMsg("Edit successfully")
            }).catch(() => {
                setMsg("error")
            })
    }
    const deletePost = () => {
        axios.delete(`https://jsonplaceholder.typicode.com/posts/${selectPost.id}`)
            .then((response) => {
                console.log("successfully add")
                setData({
                    title: "",
                    body: ""
                })
                setMsg("delete successfully")
            }).catch(() => {
                setMsg("error")
            })
    }
    useEffect(() => {
        setData({
            title: selectPost ? selectPost.title : "",
            body: selectPost ? selectPost.body : ""
        })
    }, [selectPost])
    return (
        <>
            <Row>
                <h3>Add Post</h3>
                <Col>
                    <Input
                        autoComplete="off"
                        autoFocus
                        type='textarea'
                        id="title"
                        placeholder='title'
                        value={data.title}
                        onChange={(e) => setData({ ...data, title: e.target.value, })}
                        className={'post-title'}
                    />

                </Col>
                <Col>
                    <Input
                        autoComplete="off"
                        autoFocus
                        type='textarea'
                        id="body"
                        value={data.body}
                        placeholder='body'
                        onChange={(e) => setData({ ...data, body: e.target.value })}
                        className={'post-body'}
                    />

                </Col>
                <Col>
                    <Button className="post-button" onClick={() => addPost()}>Add Post</Button>
                    <Button className="post-button" onClick={() => editPost()}>Edit Post</Button>
                    <Button className="post-button" onClick={() => deletePost()}>Delete Post</Button>
                </Col>
                <Col>
                    <h3>{msg}</h3>
                </Col>

            </Row>
            {post.length !== 0 ? <DataTable posts={post} setSelectPost={setSelectPost} /> : null}

        </>
    )
}

Datatable.js

import React, { useState } from 'react'
import DataTable from 'react-data-table-component'
import ReactPaginate from 'react-paginate';
import { CustomInput } from 'reactstrap'

export default function Datatable({ posts, setSelectPost }) {
    console.log("postspostspostsposts", posts)
    const columns = [
        {
            name: '',
            cell: (row, index) => {
                return (<CustomInput
                    type='radio'
                    name="post"
                    id={`post${index}`}
                    onChange={(e) => setSelectPost(row)}
                />)
            },
            minWidth: '50px'
        },
        {
            name: 'Id',
            minWidth: '40px',
            selector: 'userId',
            sortable: true,
            cell: (row) => row.id
        },
        {
            name: 'Title',
            minWidth: '200px',
            selector: 'title',
            sortable: true,
            cell: (row) => row.title
        },
        {
            name: 'Body',
            selector: 'body',
            minWidth: '120px',
            sortable: true,
            cell: (row) => row.body
        },
    ]
    const [dataArray11, setDataArray11] = useState(posts.slice(0, 10))
    const [currentPage, setCurrentPage] = useState(0)

    const handlePagination = (page) => {
        setCurrentPage(page.selected)
        const dataarr = []
        for (let index = page.selected * 10; index < (page.selected + 1) * 10; index++) {
            dataarr.push(posts[index])
        }
        setDataArray11(dataarr)
    }
    const CustomPagination = () => {
        return (
            <ReactPaginate
                pageCount={posts.length / 10}
                forcePage={currentPage}
                onPageChange={page => handlePagination(page)}
                activeClassName='active'
            />
        )
    }
    return (
        <DataTable
            pagination
            responsive
            paginationServer
            columns={columns}
            data={dataArray11}
            paginationComponent={CustomPagination}

        />
    )
}

Here, in the app.js add a post js file to execute first

In the post.js file, we have to display the post data which is come from API and call using the Axios method

On click add button call POST API and add post data you have to add in textarea. if add the data successfully then it will return a response to success.

On click edit button call PUT API and update with API data which is selected in a data table row. if an update of the data is successfully it will return a response to success otherwise give an error.

On click delete button call DELETE API and delete the data from API which is selected in a data table row. if delete the data successfully it will return a response to success otherwise give an error.

GET API call is give all data from called API and if successful it is returned success message.

You can see below the Axios how can perform.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories