NodeJS + Express + React Hooks + MySQL – #4 Create

NodeJS + Express

Controller

src/controllers/CustomerController.js

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

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

  try {

    const { name, email, address, phone  } = req.body;

    const data = await Customers.create({
      name: name,
      email: email,
      address: address,
      phone: phone
    })
    .then(function(data){
      const res = { success: true, data: data, message:"Saved success" }
      return res;
    })
    .catch(error =>{
      const res = { success: false, message: error }
      return res;
    })

    res.json(data);

  } catch (e) {
    const data = { success: false, message: error }
    res.json(data);
  }

};


module.exports = controller;

Routes

src/routes/api.js

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

router.post('/customer/create', customerController.create );

module.exports = router;

React

Axios

npm install axios

Form

src/views/js/components/customer/Form.js

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

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

function Form(){

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

  const [ error, setError ] = useState(null);

  const onClickSave = async () => {

    setError(null)

    const datapost = { name, email, address, phone }

    const res = await customerService.save(datapost);

    if (res.success) {
      alert(res.message)
    }
    else {
      setError(res.message)
    }

  }

  return(
    <div>
      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="firstName">Name</label>
          <input type="text" class="form-control" placeholder="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]"
          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"
          onChange={(event)=>setAddress(event.target.value)}/>
        </div>
      </div>

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

      {
        error&&
        <div class="alert alert-danger" role="alert">
          {error}
        </div>
      }


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

export default Form;

Services

src/views/js/services/Customer.js

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

customer.save = async (data) => {
  const urlSave= baseUrl+"/create"
  const res = await axios.post(urlSave,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 *