article

Tuesday, July 18, 2023

React JS Node Express JS CRUD (Create, Read, Update and Delete) | Axios Mysql

React JS Node Express JS CRUD (Create, Read, Update and Delete) | Axios Mysql

React JS
https://create-react-app.dev/

Create Project
C:\react-js>npx create-react-app my-app

Run
C:\react-js\my-app> npm start

C:\react-js\my-app\src\App.js
//C:\react-js\my-app\src\App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Add from "./components/Add";
import Read from "./components/Read";
import Users from "./components/Users";
import Update from "./components/Update";

function App() {
  return (
    <div className="app">
      <BrowserRouter>
        <Routes>
          <Route path="/add" element={<Add />} />
          <Route path="/read/:id" element={<Read />} />
          <Route path="/" element={<Users />} />
          <Route path="/update/:id" element={<Update />} />
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;
C:\react-js\my-app\src\components\Users.js
//C:\react-js\my-app\src\components\Users.js
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import axios from "axios";
import { Link } from "react-router-dom";

const Users = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const fetchAllUsers = async () => {
      try {
        const res = await axios.get("http://localhost:3001/users");
        setUsers(res.data);
      } catch (err) {
        console.log(err);
      }
    };
    fetchAllUsers();
  }, []);

  console.log(users);

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:3001/users/${id}`);
      window.location.reload()
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <div className="container">
    <h2 className='w-100 d-flex justify-content-center p-3'>React JS Node Express JS CRUD (Create, Read, Update and Delete) | Axios Mysql</h2>
        <div className='row'>
            <div className='col-md-12'>
            <p><Link to="/add" className="btn btn-success">Add new users</Link></p>
            <table className="table table-bordered">
            <thead>
                <tr>
                    <th>S No.</th>
                    <th>Full Name</th>
                    <th>Email</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                {
                    users.map((user, i) => {
                        return (
                            <tr key={i}>
                                <td>{i + 1}</td>
                                <td>{user.name} </td>
                                <td>{user.email} </td>
                                <td>
                                    <Link to={`/read/${user.id}`} className="btn btn-success mx-2">Read</Link>
                                    <Link to={`/update/${user.id}`} className="btn btn-info mx-2">Edit</Link>
                                    <button onClick={()=>handleDelete(user.id)} className="btn btn-danger">Delete</button>
                                </td>
                            </tr>
                        )
                    })
                }
            </tbody>
        </table>
        </div>
        </div>
    </div>
  );
};

export default Users;
C:\react-js\my-app\src\components\Add.js
//C:\react-js\my-app\src\components\Add.js
import axios from "axios";
import React from "react";
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";

const Add = () => {
  const [users, setUser] = useState({
    name: "",
    email: "",
    password: "",
  });

  const navigate = useNavigate();

  const handleChange = (e) => {
    setUser((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleClick = async (e) => {
    e.preventDefault();
    try {
      await axios.post("http://localhost:3001/create", users);
      navigate("/");
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <div className="container">
    <h2 className='w-100 d-flex justify-content-center p-3'>Add New User</h2>
        <div className='row'>
            <div className='col-md-12'>
                <h3>Add Your Detail</h3>
                <form>
                    <div className="mb-3 mt-3">
                        <label className="form-label"> Full Name:</label>
                        <input type="text" className="form-control" id="name" placeholder="Enter Your Full Name" name="name" onChange={handleChange} />
                    </div>
                    <div className="mb-3 mt-3">
                        <label className="form-label">Email:</label>
                        <input type="email" className="form-control" id="email" placeholder="Enter email" name="email" onChange={handleChange} required/>
                    </div>
                    <div className="mb-3 mt-3">
                        <label className="form-label">Password:</label>
                        <input type="text" className="form-control" id="password" placeholder="Enter password" name="password" onChange={handleChange} required/>
                    </div>
                     
                    <button type="submit" className="btn btn-primary" onClick={handleClick}>Add User</button>
                    <Link to="/">See all users</Link>
                </form>
            </div>
        </div>
</div>
  );
};

export default Add;
C:\react-js\my-app\src\components\Read.js
//C:\react-js\my-app\src\components\Read.js
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import axios from "axios";
import { useParams } from "react-router-dom";

const Read = () => {
    const {id} = useParams();
    const [user, setUsers] = useState([]);

    useEffect(() => {
        axios.get("http://localhost:3001/userdetails/"+id)
        .then(res => {
            console.log(res)
            setUsers(res.data[0]);
        })
        .catch(err => console.log(err))
    }, []);

  return (
    <div className="container">
        <div className='row'>
        <div className='col-md-12'>
        <h1>User Details</h1>
            <table className="table">
                <thead>
                    <tr>
                        <th>S No.</th>
                        <th>Full Name</th>
                        <th>Email</th> 
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>{user.id}</td>
                        <td>{user.name}</td>
                        <td>{user.email}</td>
                    </tr>
                </tbody>
            </table>
      </div>
      </div>
    </div>
  );
};

export default Read;
C:\react-js\my-app\src\components\Update.js
//C:\react-js\my-app\src\components\Update.js
import axios from "axios";
import React, { useState, useEffect } from "react";
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";

const Update = () => {
    const {id} = useParams();
    const [user, setUser] = useState({
        name: "",
        email: "",
        password: "",
    });

    const location = useLocation();
    const navigate = useNavigate();

    const userId = location.pathname.split("/")[2];

    const handleChange = (e) => {
        setUser((prev) => ({ ...prev, [e.target.name]: e.target.value }));
    };

    useEffect(() => {
        axios.get("http://localhost:3001/userdetails/"+id)
        .then(res => {
            console.log(res)
            setUser(res.data[0]);
        })
        .catch(err => console.log(err))
    }, []);

    const handleClick = async (e) => {
        e.preventDefault();

        try {
            await axios.put(`http://localhost:3001/users/${userId}`, user);
            navigate("/");
        } catch (err) {
            console.log(err);
        }
    };

  return (
    <div className="container">
    <h1>Edit Form</h1>
        <form>
                <div className="mb-3 mt-3">
                    <label className="form-label"> ID:</label>
                    <input type="text" className="form-control" id="id" placeholder="Enter Your Full Name" name="id" value={id} disabled />
                </div>
                <div className="mb-3 mt-3">
                    <label className="form-label"> Full Name:</label>
                    <input type="text" className="form-control" placeholder="Enter Your Full Name" name="name" value={user.name} onChange={handleChange} />
                </div>
                <div className="mb-3 mt-3">
                    <label className="form-label">Email:</label>
                    <input type="email" className="form-control" id="email" placeholder="Enter email" name="email" value={user.email}  onChange={handleChange}/>
                </div>
                <div className="mb-3 mt-3">
                    <label className="form-label">Password:</label>
                    <input type="password" className="form-control" id="password" placeholder="Enter password" name="password" value={user.password} onChange={handleChange}/>
                </div>
                <button type="submit" className="btn btn-primary" onClick={handleClick}>Update</button>
        </form>
        <div className='container d-flex justify-content-center'>
            <Link to="/">See all users</Link>
        </div>
    </div>
  );
};

export default Update;
Install axios
https://github.com/axios/axios

Installing the Axios Client

$ npm install axios
C:\reactdev\myreactdev>npm install axios

Install React Router Dom
https://www.npmjs.com/package/react-router-dom
C:\react-js\myreactdev>npm i react-router-dom --save

react-js\my-app\public\index.html
//react-js\my-app\public\index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
  </head>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
Run C:\react-j\my-app>npm start
http://localhost:3000/

https://expressjs.com/
Express JS
Fast, unopinionated, minimalist web framework for Node.js

Install
$ npm install express --save
PS C:\nodeproject> npm install express --save

https://expressjs.com/en/starter/hello-world.html
run
PS C:\nodeproject> node index.js

//C:\nodeproject> node index.js 
const express = require("express");
const app = express();
const mysql = require("mysql"); // https://github.com/mysqljs/mysql npm install mysqljs/mysql
const cors = require("cors"); //https://www.npmjs.com/package/cors npm i cors
  
//const port = 3000
  
app.use(cors());
app.use(express.json());

const db = mysql.createConnection({
  user: "root",
  host: "localhost",
  password: "",
  database: "nodejsdb",
});

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.get("/users", (req, res) => {
  const q = "SELECT * FROM users";
  db.query(q, (err, data) => {
    if (err) {
      console.log(err);
      return res.json(err);
    }
    return res.json(data);
  });
});

app.post("/create", (req, res) => {
    const name = req.body.name;
    const email = req.body.email;
    const password = req.body.password;
    
    db.query(
      "INSERT INTO users (name, email, password) VALUES (?,?,?)",
      [name, email, password],
      (err, result) => {
        if (err) {
          console.log(err);
        } else {
          res.send("You have registered successfully!");
        }
      }
    );
}); 

app.get("/userdetails/:id", (req, res) => {
  const id = req.params.id;
  db.query("SELECT * FROM users WHERE id = ?", id, (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

app.delete("/users/:id", (req, res) => {
  const userId = req.params.id;
  const q = " DELETE FROM users WHERE id = ? ";

  db.query(q, [userId], (err, data) => {
    if (err) return res.send(err);
    return res.json(data);
  });
});

app.put("/users/:id", (req, res) => {
  const userId = req.params.id;
  const q = "UPDATE users SET `name`= ?, `email`= ?, `password`= ? WHERE id = ?";

  const values = [
    req.body.name,
    req.body.email,
    req.body.password,
  ];

  db.query(q, [...values,userId], (err, data) => {
    if (err) return res.send(err);
    return res.json(data);
  });
});

//app.listen(port, () => {
//  console.log(`Example app listening on port ${port}`)
//})

app.listen(3001, () => {
    console.log("Yey, your server is running on port 3001");
});
Install Requirements

mysql
https://github.com/mysqljs/mysql
$ npm install mysql
PS C:\nodeproject>npm install mysql

cors
CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.
https://www.npmjs.com/package/cors
PS C:\nodeproject>npm i cors

Related Post