useState post api
Fri Aug 05 2022 13:28:25 GMT+0000 (Coordinated Universal Time)
Saved by
@DGSH
//javascript
// Manage state
const [employee, setEmployee] = useState(
{
id: "",
firstName: "",
lastName: "",
emailId: ""
}
);
//function to insert value in state
const handleChange = (e) => {
const value = e.target.value;
setEmployee({ ...employee, [e.target.name]: value });
};
//call api to save
const saveEmployee = (e) => {
// e.preventDefault();
EmployeeService.saveEmployee(employee).then((response) => {
console.log(response);
}).catch((err) => {
console.log(err);
})
};
=================>JSX
{/* For Email */}
<div className='items-center justify-center h-14 w-full my-4'>
<label className='block text-grey-600 text-sm fornt-normal'>Email</label>
<input type="text" className='h-10 w-96 border mt-2 px-2 py-2'
name="emailId"
value={employee.emailId}
onChange={(e) => handleChange(e)}
></input>
</div>
{/* For Button */}
<div className='items-center justify-center h-14 w-full my-8'>
<button onClick={saveEmployee} className='rounded'>Save</button>
<button className='rounded'>Clear</button>
</div>
=================>Calling api class
import axios from "axios";
const EMPLOYEE_API_BASE_URL = "http://localhost:8080/api/v1/employees";
class EmployeeService {
//post api(save)
saveEmployee(employee) {
return axios.post(EMPLOYEE_API_BASE_URL, employee);
};
}
export default new EmployeeService();
content_copyCOPY
Comments