Crud operation in react.js using the function component using and json server.

 In this tutorial we are going to learn about how to do crud operation in react function components using json server. How to call a json server using axios in the front end. How to get data using function components. How to delete, put and post requests in the function component and also learn about useEffect hook.


First you need to create a react app using cmd to input npx create-react-app [your app name] . In my case my app name is crud.


Folder structure:-

In src create a separate folder called components where we can store  our components of this app.


Create several files which are AddData.js here we write a code for adding data to our table , second is UpdateData.js here we write a code for update or data in particular column, third one is ManeTable.js here we write code for get data from json server and print in table format.


Also create one more folder that is Data. In this data folder we create a db.json file where we can store our table data in json format .


Npm :-

Before coding we need to install some npm. First is axios for making requests from the json server , we can install axios npm by using npm i axios command in cmd . Second is json-server which is used to create a backend server without any coding , for a front end developer who needs a quick backend for testing and mocking. Here we use json server for creating simple backend. Npm i json-server for installing this package.


Third one is react-router-dome which is used for creating routing in our application. Npm i react-router-dome this is command which is use for installing this package 














Code :-


We use bootstrap 4 for creating ui. First of all we need to copy cdn link from bootstrap website and past it on index.html in public folder.

 


You can check the bootstrap website for more details.


Now step by step create all components that we need on this application .


NaveBar.js component:-

First we create a navbar component for our application. Go to the bootstrap website and search navbar and copy the code as you need and modify the code.


This following code is a navbar component. I modify the code as per my need. You should copy the following code or you create as you need.


import React from 'react'

import { Link } from "react-router-dom";

 

export default function Navebar() {

    return (

 

        <div>

            <nav class="navbar navbar-expand-lg navbar-light bg-light">

                <Link class="navbar-brand" to="/">user</Link>

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav"

                    aria-expanded="false" aria-label="Toggle navigation">

                    <span class="navbar-toggler-icon"></span>

                </button>

                <div class="collapse navbar-collapse" id="navbarNav">

                    <ul class="navbar-nav">

                        <li class="nav-item">

                            <Link class="nav-link" to="/add">Add user</Link>

                        </li>

                    </ul>

                </div>

            </nav>

        </div>

    )

}


Copy the following code as you need and create a form component like this.


AddData.js component:-

Go to the bootstrap form and copy the form code to create the addData component for our application.


This following code is modified as per my need. You should copy this code.


return (

        <div className="container-fluid">

            <form onSubmit={e => onSubmit(e)}>

                <div class="form-group">

                    <label for="exampleInputEmail1">name</label>

                    <input type="name" class="form-control"

                        name="name"

                        value={name}

                        onChange={e => onInputChange(e)} />

                </div>

                <div class="form-group">

                    <label for="exampleInputEmail1">Email address</label>

                    <input type="email" class="form-control"

                        name="email"

                        value={email}

                        onChange={e => onInputChange(e)} />

                </div>

                <div class="form-group">

                    <label for="exampleInputEmail1">phone</label>

                    <input type="phone" class="form-control"

                        name="phone"

                        value={phone}

                        onChange={e => onInputChange(e)} />

                </div>

                <button type="submit" class="btn btn-primary">log in</button>

            </form>

        </div>

    )

}


So you create components like this.



UpdateData.js component is same as AddData component.



return (

        <div className="container">

            <form onSubmit={e => onSubmit(e)}>

                <div className="form-group">

                    <label for="exampleInputEmail1">Email address</label>

                    <input type="email" class="form-control"

                        name="email"

                        value={email}

                        onChange={e => onInputeChange(e)}

                    />

                </div>

                <div className="form-group">

                    <label for="exampleInputEmail1">Name</label>

                    <input type="name" class="form-control"

                        name="name"

                        value={name}

                        onChange={e => onInputeChange(e)}

                    />

                </div>

                <div className="form-group">

                    <label for="exampleInputEmail1">password</label>

                    <input type="phone" class="form-control"

                        name="phone"

                        value={phone}

                        onChange={e => onInputeChange(e)}

                    />

                </div>

                <button type="submit" class="btn btn-primary">update</button>

            </form>

        </div>

    )

}



ManeTable.js component:-

Go to the bootstrap table and copy the code of table 



return (

        <div className="container-fluid">

            <table className="table table-bordered">

                <thead>

                    <tr>

                        <th scope="col">id</th>

                        <th scope="col">name</th>

                        <th scope="col">email</th>

                        <th scope="col">phone</th>

                        <th scope="col">action</th>

                    </tr>

                </thead>

                <tbody>

                    {users.map(user => (

                        <tr>

                            <th scope="row">{user.id}</th>

                            <td>{user.name}</td>

                            <td>{user.email}</td>

                            <td>{user.phone}</td>

                            <td>

                                <Link

                                    class="btn btn-danger"

                                    onClick={() => deleteUser(user.id)}

                                >

                                    Delete

                                </Link>

                                <Link

                                    className="btn btn-primary"

                                    to={`/edit/${user.id}`}

                                >

                                    Edit

                                </Link>

                            </td>

                        </tr>

                    ))

                    }

                </tbody>

            </table>

        </div>

    )

}


And this look like that



You need to run the following command on cmd to run json-server.

json-server --watch data/db.json --port 5000


To get data from the api using the function component we use useState hook it is the same as state in class component. 


First we create a function loadUser() . and make a get request from api using axios. And pass the data to setUser . And pass this function to useEffect hook . useEffect is the same as componentdidmount in class component.  


const [users, setUser] = useState([]);

 

    useEffect(() => {

        loadUsers();

    }, []);

 

    const loadUsers = async () => {

        const result = await axios.get("http://localhost:5000/users");

        setUser(result.data.reverse()); 

};

 

Now use the map method to print data which you get by the api.


<tbody>

                    {users.map(user => (

                        <tr>

                            <th scope="row">{user.id}</th>

                            <td>{user.name}</td>

                            <td>{user.email}</td>

                            <td>{user.phone}</td>

 

Create delete request :-

Create deleteUser function for deleting a particular row , for this we need the id of the user. 


const deleteUser = async id => {

        await axios.delete(`http://localhost:5000/users/${id}`);

        loadUsers();

    };


Create a button and pass the deleteUser function to the button. 


<Link

                                    class="btn btn-danger"

                                    onClick={() => deleteUser(user.id)}

                                >

                                    Delete

                                </Link>



Update component:-

For updating a column we need the id of a particular column .


<Link

                                    className="btn btn-primary"

                                    to={`/edit/${user.id}`}

                                >

                                    Edit

                                </Link>


For getting an id we need to define a path with an id param.


The id which passed in the url gets in the UpdateData.js component by using useParams hook. So we can update the particular column.


Also we use the spread operator which i explain in this post so please go and checkout for better understanding. Spread operator updates a particular targeted value by using value and name as a params. By using onInputeCange function and pass the value to setUser in useState as an updated value. And this updated value passing users and at the last creating an onsubmit function using this function pass the data to api . 




Github link:-


Post a Comment

0 Comments