CRUD – Spring Boot + ReactJS + API Rest + MySQL #8 Update

Spring – Backend

Controller

src/main/java/com/tutofox/demo/controllers/EmployeeController.java

package com.tutofox.tutospring.controllers;
/.../
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
	
  /.../
	
	@PutMapping(value="/update/{id}")  
	public Map<String, Object> update(@PathVariable("id") Integer id,
			@RequestBody Employee data ){
		
		HashMap<String,Object> response = new HashMap<String,Object>();
		
		try {  
			data.setId(id);
			employeeRepository.save(data);
			response.put("message","Successful update"); 
			response.put("success",true);
			return response;
		} catch (Exception e) {
			response.put("message",e.getMessage()); 
			response.put("success",false);
			return response;
		}
		
	} 

	 
}

ReactJS – Frontend

Services Employee

src/main/resources/js/components/services/Employee.js

const baseUrl = "http://localhost:8080/api/employee"
import axios from "axios";
const employee = {};

employee.update = async (state) => {

  const datapost = {
    name: state.fieldName,
    email: state.fieldEmail,
    phone: state.fieldPhone,
    address: state.fieldAddress
  }

  const urlUpdate = baseUrl+"/update/"+state.id

  const res = await axios.put(urlUpdate,datapost)
  .then(response=>{ return response.data })
  .catch(error=>{ return error.response })

  return res;
}

export default employee

Edit

src/main/resources/js/components/employee/Edit.js

Button

<button class="btn btn-primary btn-block" onClick={()=>this.onClickUpdate()}
		      		type="submit">Update</button>

onClickUpdate

async onClickUpdate()
{ 
    console.log("Execute update");
	const res = await employeeServices.update(this.state)
	if (res.success) {
		alert(res.message)
	}
	else {
      console.log("Error");
      console.log(res);
		alert("Error ==>"+JSON.stringify(res.data))
	}
}

Edit.js – all source code

import React, { Component } from 'react';

import employeeServices from "../services/Employee"

export default class Edit extends Component {

  constructor(){
    super()
    this.state = {
      id:0,
      fieldName:"",
      fieldEmail:"",
      fieldPhone:"",
      fieldAddress:""
    }
  }

  async componentDidMount()
  {
     console.log("Mounted Edit");
     const id = this.props.match.params.id;
     const res = await employeeServices.get(id)
     console.log(res);
     if (res.success) {
       console.log(res.data);
        this.setState({
          id: res.data.id,
          fieldName:res.data.name,
          fieldEmail:res.data.email,
          fieldAddress:res.data.address,
          fieldPhone:res.data.phone
        })
     }
     else {
       alert("Error ==>"+res.message)
     }
  }

  render() {
    let userId = this.props.match.params.id;
    return (
      <div>
        <h4>Edit Employee {userId} v2 </h4>
        <hr />
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="firstName">Name employee</label>
            <input type="text" class="form-control"
              value={this.state.fieldName}
              onChange={(value)=>this.setState({fieldName:value.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={this.state.fieldEmail}
              onChange={(value)=>this.setState({fieldEmail:value.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={this.state.fieldAddress}
              onChange={(value)=>this.setState({fieldAddress:value.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={this.state.fieldPhone}
              onChange={(value)=>this.setState({fieldPhone:value.target.value})}
            />
          </div>
        </div>

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

	async onClickUpdate()
	{ 
    console.log("Execute update");
		const res = await employeeServices.update(this.state)
		if (res.success) {
			alert(res.message)
		}
		else {
      console.log("Error");
      console.log(res);
			alert("Error ==>"+JSON.stringify(res.data))
		}
	}

}

Deja una respuesta

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