Ad Code

✨🎆 Diwali Dhamaka Offer! 🎆✨

Get 20% OFF on All Courses at Shiva Concept Solution click

Local JSON file CRUD Operation using Fetch API in React JS, How to Access API with local json file in react


In this article, I am describing, how to create a local JSON server and perform CRUD operation using React-JS Project.

Step1st:

Create React Project 

npx create-react-app projectname

Step 2nd:-

Create db.json file under public folder and write this code

{
  "posts": [
    {
      "id": 1,
      "name": "Satheesh",
      "email": "Sat@mail.com",
      "adderss": "South street"
    },
    {
      "id": 2,
      "name": "John",
      "email": "john@mail.com",
      "adderss": "North street"
    },
    {
      "id": 3,
      "name": "Robert",
      "email": "robert@mail.com",
      "adderss": "East street"
    },
    {
      "id": 4,
      "name": "Mani",
      "email": "mani@mail.com",
      "adderss": "West street"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

Step 3rd:-
Install JSON Server under same project
npm install -g Json-server 

Step 4th:-
Open Command Prompt  under public folder and write following command
json-server –-watch db.json --port 3001

Step5th:-

Create Component to Access GET API using Fetch and Write this code

import React from "react";

export default class Restapiget extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {tdata:[]}
    }
    componentDidMount() {

        fetch('http://127.0.0.1:3001/posts')

        .then(res => res.json())

        .then((data) => {

          this.setState({ tdata: data })

          console.log(this.state.tdata)

        })

        .catch(console.log)

      }
    render(){
        return(<div>
         <table border='1'>
            <tr><th>UserId</th><th>Name</th><th>Email</th><th>Address</th></tr>
            {this.state.tdata.map((person,i)=>  
             <tr key={i}>
                <td>{person.id}</td>
                <td>{person.name}</td>
                <td>{person.email}</td>
                <td>{person.adderss}</td>
                <td>Edit</td>
                <td>Delete</td>
            </tr>)}  
         </table>
        </div>)
    }
}

Create RESTFUL API for POST
import React from "react";

export default class Restapipost extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {tdata:''}
    }
    componentDidMount() {

        fetch('http://127.0.0.1:3001/posts',{
         method: 'POST',
         body: JSON.stringify({
          id:'5',
          name:'mno',
          email:'1023',
          adderss:'Test address'
      }),
         headers:{"content-type":"application/json; charset=UTF-8"}  
          }).then(res => res.json())

    .then((data) => {

       console.log(data)
       this.setState({tdata:data})

    }).catch(console.log)
   }
         
    render(){
        return(<div>
           
            <h1>{this.state.tdata.id}</h1>
        </div>)
    }
}

Create RESTFULT API for UPDATE
import React from "react";

export default class Restapiput extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {tdata:''}
    }
    componentDidMount() {

        fetch('http://127.0.0.1:3001/posts/'+5,{
         method: 'PUT',
         body: JSON.stringify({
          name:'klmn',
          email:'klmn@gmail.com',
          adderss:'Test address'
      }),
         headers:{"content-type":"application/json; charset=UTF-8"}  
          }).then(res => res.json())

    .then((data) => {

       console.log(data)
       this.setState({tdata:'update success'})

    }).catch(console.log)
   }    
   
    render(){
        return(<div>
           
            <h1>{this.state.tdata}</h1>
        </div>)
    }
}

Create RESTFULL API for Delete:-

import React from "react";

export default class Restapidelete extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {tdata:''}
    }
    componentDidMount() {

        fetch('http://127.0.0.1:3001/posts/'+5,{
         method: 'DELETE'
          });
   }
      
    render(){
        return(<div>
           
            <h1>Delete Success</h1>
        </div>)
    }
}

...................................................................

POST and Update Operation taking user input:-

import React from "react";

export class RestAPIPostExample extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {sid:'',name:'',email:'',address:'',data:''}
    }
    updatedata=(e)=>{
        fetch('http://127.0.0.1:3001/posts/'+this.state.sid,{
            method: 'PUT',
            body: JSON.stringify({
             name:this.state.name,
             email:this.state.email,
             adderss:this.state.address
         }),
            headers:{"content-type":"application/json; charset=UTF-8"}  
             }).then(res => res.json())
   
       .then((data) => {
   
          console.log(data)
          this.setState({data:'Update Successfully'})
   
       }).catch(console.log)
       e.preventDefault();
    }
       
   
   postdata=(e)=>{
   
        fetch('http://127.0.0.1:3001/posts',{
            method: 'POST',
            body: JSON.stringify({
             id:this.state.sid,
             name:this.state.name,
             email:this.state.email,
             adderss:this.state.address
         }),
            headers:{"content-type":"application/json; charset=UTF-8"}  
             }).then(res => res.json())
   
       .then((data) => {
   
          console.log(data)
          this.setState({data:'Insert Successfully'})
   
       }).catch(console.log)
       e.preventDefault();
       
    }

    render()
    {
        return(<div>
            <h1>Insert Record Here</h1>
            <form>
            <input type="text" onChange={(e)=>{this.setState({sid:e.target.value})}} placeholder="Enter ID" />
             <br/>
             <input type="text" onChange={(e)=>{this.setState({name:e.target.value})}} placeholder="Enter Name"  />
             <br/>
             <input type="text" onChange={(e)=>{this.setState({email:e.target.value})}} placeholder="Enter Email" />
             <br/>
             <input type="text" onChange={(e)=>{this.setState({address:e.target.value})}} placeholder="Enter Address" />
             <br/>
             <input type="submit" value="Postdata" id="insert" onClick={this.postdata} />
             <input type="submit" value="Updatedata" id="update" onClick={this.updatedata} />
            </form>
            <h1>{this.state.data}</h1>
        </div>)
    }
}



Delete Operation taking from user Input:-

import React from "react";

export class RestAPIDeleteExample extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {sid:'',data:''}
    }
   postdata=(e)=>{
        fetch('http://127.0.0.1:3001/posts/'+this.state.sid,{
            method: 'Delete'}).then(res => res.json()).then((data) => {
           console.log(data)
          this.setState({data:'Delete Successfully'})
   
       }).catch(console.log)
       e.preventDefault();
    }
    render()
    {
        return(<div>
            <h1>Delete Record Here</h1>
            <form onSubmit={this.postdata}>
            <input type="text" onChange={(e)=>{this.setState({sid:e.target.value})}} placeholder="Enter ID" />
            <br/>
            <input type="submit" value="Deletedata" />
            </form>
            <h1>{this.state.data}</h1>
        </div>)
    }
}


Post a Comment

0 Comments