NodeJS + Express + React Hooks + MySQL – #7 Update

NodeJS + Express

Controller

src/controllers/CustomerController.js

const controller = {}
// import model
var Customers = require('../models/Customers');

 
controller.update = async ( req, res ) =>{

  try {

    // parameter get id
    const { id } = req.params;
    // parameter POST
    const { name, email, address, phone } = req.body;
    // Update data
    const response = await Customers.update({
      name:name,
      email:email,
      address:address,
      phone:phone
    },
    {
      where: { id: id }
    })
    .then( function(data){
      const res = { success: true, message:"Customer successfully updated" }
      return res;
    })
    .catch(error => {
      const res = { success: false, message: error.message }
      return res;
    })

    res.json(response);

  } catch (e) {

    const response = { succes: false, message: e.message }
    res.json(response)

  }  
}

module.exports = controller;

Routes

src/routes/api.js

const express = require('express');
const router = express.Router();
//import controller
const customerController = require('./../controllers/CustomerController');

router.put('/customer/update/:id', customerController.update);

module.exports = router;

React

SweetAlert

npm install sweetalert --save

Form

src/views/js/components/customer/Edit.js

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

import customerService from "../../services/Customer"

import swal from 'sweetalert';

function Edit(props){

  const [ id, setId ] = useState(null)
  const [ name, setName ] = useState(null);
  const [ email, setEmail ] = useState(null);
  const [ address, setAddress ] = useState(null);
  const [ phone, setPhone ] = useState(null);

  useEffect(()=>{

    async function fetchDataCustomer(){

      let id = props.match.params.id;
      const res = await customerService.get(id);

      if (res.success&&res.data) {

        const data = res.data
        console.log(data);
        setId(data.id);
        setName(data.name);
        setEmail(data.email);
        setAddress(data.address);
        setPhone(data.phone);

      }
    }
    fetchDataCustomer();

  },[])

  const onClickUpdate = async () => {

    const data = { id, name, email, address, phone }

    const res = await customerService.update(data);

    if (res.success) {
      swal(res.message," ", "success");
    }
    else {
      swal("Error!", ""+JSON.stringify(res.message), "error"); 
    }

  }

  return (
    <div>
      <h4>Edit customer  {id}  </h4>
      <hr/>
      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="firstName">Name</label>
          <input type="text" class="form-control" placeholder="Name" value={name}
          onChange={(event)=>setName(event.target.value)}/>
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="email">Email</label>
          <input type="email" class="form-control" placeholder="[email protected]" value={email}
          onChange={(event)=>setEmail(event.target.value)}/>
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="address">Address</label>
          <input type="text" class="form-control" placeholder="1234 Main St"  value={address}
          onChange={(event)=>setAddress(event.target.value)}/>
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="address">Phone </label>
          <input type="text" class="form-control" placeholder="123467890"  value={phone}
          onChange={(event)=>setPhone(event.target.value)}/>
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
          <button  onClick={()=>onClickUpdate()}
          class="btn btn-primary btn-block" type="submit">Save</button>
        </div>
      </div>
    </div>
  )

}

export default Edit;

Services

src/views/js/services/Customer.js

const baseUrl = "http://localhost:3000/api/customer"
import axios from "axios";
const customer = {};

customer.update = async (data) => {
  const urlUpdate = baseUrl+"/update/"+data.id
  const res = await axios.put(urlUpdate,data)
  .then(response=>{ return response.data; })
  .catch(error => { return error; })
  return res;
}
 
export default customer

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *