React-Hook-Form Validation - reactjs

I'm looking to implement the form validation using react-hook. However, I'm facing some trouble in doing so as I've also added some stuff on my own under the handleSubmit and I'm not really sure how to go about it.
export default function Contact() {
const [message, setMessage] = useState(false);
const [alert, setAlert] = useState(true);
const { register, errors} = useForm();
const [showElement, setShowElement] = React.useState(false);
const handleSubmit = (e) => {
e.preventDefault();
emailjs.sendForm('', '', e.target, '')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
e.target.reset();
setMessage(true);
setShowElement(true);
setTimeout(function () {
setShowElement(false);
}, 4000);
};
const onSubmit= data=>{
console.log(data);
}
return (
<div className="right">
<h2>Contact Me</h2>
<form onSubmit={handleSubmit} id="contactform">
<input type="text" placeholder="Name" name="name" ref={register({required: true, minLength: 2})}
required />
<button type="submit">Send</button>
</form>
{showElement ? (
<div className="submitmsg">
{message && (
<span> Messaged received. I'll respond to your query ASAP! </span>
)}
</div>
) : (
<div> </div>
)}{" "}
</div>
)
}
Thank you!

React hook form provides the handeSubmit method that receives the form data after validations. Also, you must use the errors object to show errors in the UI.
Here is the sandbox link: https://codesandbox.io/s/exciting-dust-df5ft?file=/src/App.js
I have updated your code accordingly:
import { useState } from "react";
import React from "react";
import emailjs from "emailjs-com";
import { useForm } from "react-hook-form";
export default function Contact() {
const [message, setMessage] = useState(false);
const {
register,
handleSubmit,
formState: { errors }
} = useForm();
const [showElement, setShowElement] = React.useState(false);
const onSubmit = (data) => {
emailjs
.send(
"service_t1ccrgq",
"template_gmmcyzr",
data,
"user_d0vUwhmqvbIYhEsyZF8tu"
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
setMessage(true);
setShowElement(true);
setTimeout(function () {
setShowElement(false);
}, 4000);
};
return (
<div className="contact" id="contact">
<div className="left">
<img className="contactme" src="asset/email.gif" />
</div>
<div className="right">
<h2>Contact Me</h2>
<form onSubmit={handleSubmit(onSubmit)} id="contactform">
<input
type="text"
placeholder="Name"
name="name"
{...register("name", {
required: "Name is Required",
minLength: {
value: 3,
message: "Should be greater than 3 characters"
}
})}
/>
<input
type="tel"
placeholder="Mobile Number"
name="mobile"
{...register("mobile", {
required: "Mobile Number is Required",
minLength: {
value: 3,
message: "Should be greater than 3 characters"
}
})}
/>
<input
type="text"
placeholder="Email"
name="email"
{...register("email", {
required: "Email is Required",
minLength: {
value: 3,
message: "Should be greater than 3 characters"
}
})}
/>
<textarea
placeholder="Message"
required
name="message"
{...register("message", {
required: "Message is Required",
minLength: {
value: 3,
message: "Should be greater than 3 characters"
}
})}
></textarea>
<button type="submit">Send</button>
</form>
{showElement ? (
<div className="submitmsg">
{message && (
<span> Messaged received. I'll respond to your query ASAP! </span>
)}
</div>
) : (
<div> </div>
)}{" "}
</div>
{errors.name && (
<div>
<span>{errors.name.message}</span>
</div>
)}
{errors.message && (
<div>
<span>{errors.message.message}</span>
</div>
)}
{errors.email && (
<div>
<span>{errors.email.message}</span>
</div>
)}
{errors.mobile && (
<div>
<span>{errors.mobile.message}</span>
</div>
)}
</div>
);
}

You have to first initialize handleSubmit as below.
const {handleSubmit} = useForm();
Then in the form, onSubmit should be as below.
<form onSubmit={handleSubmit(onSubmit)}>
"onSubmit" is the method that is used to write the code in submitting form.
Regards.
In your code, it should be as below.
const onSubmit = (e) => {
e.preventDefault();
emailjs.sendForm('', '', e.target, '')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
e.target.reset();
setMessage(true);
setShowElement(true);
setTimeout(function () {
setShowElement(false);
}, 4000);
};

Related

React Datepicker - Uncaught RangeError: Invalid time value

Building a simple ToDo list app in ReactJS. Below is my Add Task functional component:
import React, { useState } from "react";
import TaskDataService from "../services/task.service";
import DatePicker from 'react-datepicker'
import FadeIn from 'react-fade-in';
import "react-datepicker/dist/react-datepicker.css";
import 'bootstrap/dist/css/bootstrap.min.css';
const AddTask = () => {
const initialTaskState = {
id: null,
title: "",
description: "",
completed: false,
startDate: new Date()
};
const [task, setTask] = useState(initialTaskState);
const [submitted, setSubmitted] = useState(false);
const handleInputChange = event => {
const { name, value } = event.target;
setTask({ ...task, [name]: value });
};
const saveTask = () => {
var data = {
title: task.title,
description: task.description,
startDate: task.startDate
};
TaskDataService.create(data)
.then(response => {
setTask({
id: response.data.id,
title: response.data.title,
description: response.data.description,
completed: response.data.completed,
startDate: response.data.startDate
});
setSubmitted(true);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
const newTask = () => {
setTask(initialTaskState);
setSubmitted(false);
};
return (
<FadeIn>
<div className="submit-form">
{submitted ? (
<div>
<h4>Task submitted successfully!</h4>
<button className="btn btn-success" onClick={newTask}>
Add
</button>
</div>
) : (
<div>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
className="form-control"
id="title"
required
value={task.title}
onChange={handleInputChange}
name="title"
/>
</div>
<div className="form-group">
<label htmlFor="description">Description</label>
<input
type="text"
className="form-control"
id="description"
required
value={task.description}
onChange={handleInputChange}
name="description"
/>
</div>
<div className="form-group">
<label htmlFor="startDate">Start Date</label>
<DatePicker
selected={ task.startDate }
onChange={date => handleInputChange({target: {value: date.toISOString().split("T")[0], name: 'startDate'}})}
name="startDate"
dateFormat="yyyy-MM-dd"
/>
</div>
<button onClick={saveTask} className="btn btn-success">
Submit
</button>
</div>
)}
</div>
</FadeIn>
);
}
export default AddTask;
When I try to select a date from the Datepicker calendar, app rendering crashes. There are a few errors but it looks like the main one is "Uncaught RangeError: Invalid time value". However, the task is successfully added to the database and I can view it upon reloading the app. But for whatever case, it crashes upon submit.
In contrast, this is my standalone Task component which also contains code for editing an existing task. In that component, everything works 100%. I can open the Datepicker calendar on the selected task, select a new date, and submit it succesfully with zero problems:
import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import TaskDataService from "../services/task.service";
import DatePicker from 'react-datepicker';
import FadeIn from 'react-fade-in';
const Task = props => {
const { id } = useParams();
let navigate = useNavigate();
const initialTaskState = {
id: null,
title: "",
description: "",
completed: false,
startDate: new Date(),
};
const [currentTask, setCurrentTask] = useState(initialTaskState);
const [message, setMessage] = useState("");
const getTask = id => {
TaskDataService.get(id)
.then(response => {
setCurrentTask(response.data);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
useEffect(() => {
if (id)
getTask(id);
}, [id]);
const handleInputChange = event => {
const { name ,value } = event.target;
setCurrentTask({ ...currentTask, [name]: value });
};
const updateCompleted = status => {
var data = {
id: currentTask.id,
title: currentTask.title,
description: currentTask.description,
completed: currentTask.completed,
startDate: currentTask.startDate
};
TaskDataService.update(currentTask.id, data)
.then(response => {
setCurrentTask({ ...currentTask, completed: status });
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
const updateTask = () => {
TaskDataService.update(currentTask.id, currentTask)
.then(response => {
console.log(response.data);
setMessage("The task was updated successfully!");
})
.catch(e => {
console.log(e);
});
};
const deleteTask = () => {
TaskDataService.remove(currentTask.id)
.then(response => {
console.log(response.data);
navigate("/tasks");
})
.catch(e => {
console.log(e);
});
};
return (
<FadeIn>
<div>
{currentTask ? (
<div className="edit-form">
<h4>Task</h4>
<form>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
className="form-control"
id="title"
value={currentTask.title}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="description">Description</label>
<input
type="text"
className="form-control"
id="description"
value={currentTask.description}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
{currentTask.completed ? "Completed" : "Pending"}
</div>
<div className="form-group">
<label htmlFor="startDate">Start Date</label>
<DatePicker
onChange={date => handleInputChange({target: {value: date.toISOString().split("T")[0], name: 'startDate'}})}
name="startDate"
dateFormat="yyyy-MM-dd"
value={currentTask.startDate.toString().split("T")[0]}
/>
</div>
</form>
{currentTask.completed ? (
<button
className="badge badge-primary mr-2"
onClick={() => updateCompleted(false)}
>
Mark Pending
</button>
) : (
<button
className="badge badge-primary mr-2"
onClick={() => updateCompleted(true)}
>
Mark Complete
</button>
)}
<button
className="badge badge-danger mr-2"
onClick={deleteTask}
>
Delete
</button>
<button
type="submit"
className="badge badge-success"
onClick={updateTask}
>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Please click on a Task...</p>
</div>
)}
</div>
</FadeIn>
);
}
export default Task;
Done a lot of testing and research but no dice. Any ideas?
Commenter Konrad Linkowski provided the clue to the solution. I removed the line "startDate: response.data.startDate" and now it all works. I do not fully understand, so if anyone wants to explain the answer then please feel free.

How to validate email and password using react hooks?

I am getting state values while clicking submit button but I am unable to do the validation for my login form and how to display the error messages below the input field when I enter my input wrong or empty. please give me a solution to this.Thanks in advance.
const Login = () => {
const [state, setState] = useState({
email: "",
password: ""
});
const handleChange = (e) => {
const {id, value} = e.target
setState(prevState => ({
...prevState,
[id]: value
}))
}
const handleSubmitClick = (e) => {
e.preventDefault();
console.log("Authenticated",state);
}
return(
<>
<div className="container">
<div className="title">
<form onSubmit={handleSubmitClick}>
<div className="form-group">
<input
type="email"
className="email"
placeholder="Email"
value={state.email}
onChange={handleChange}/>
</div>
<div className="form-group">
<input
type="password"
className="password"
placeholder="Password"
value={state.password}
onChange={handleChange}/>
</div>
<button type="submit" className="button">Enter</button>
</form>
</div>
</div>
</>
)
}
export default Login;
If you want to perform client-side validation, you can create hook like this:
const useEmailValidation = (email) => {
const isEmailValid = /#/.test(email); // use any validator you want
return isEmailValid;
};
And then you can use this hook in your form component:
...
const isEmailValid = useEmailValidation(state.email);
const isPasswordValid = usePasswordValidation(state.password);
const isFormValid = isEmailValid && isPasswordValid;
return (
...
<input
className={classNames({ 'invalid': !isEmailValid })}
type="email"
value={state.email}
onChange={handleChange}
/>
{!isEmailValid && 'Some error message'}
<button type="submit" disabled={!isFormValid} className="button">Enter</button>
...
);
...
Your validator hook can return validation message instead of boolean, like:
const useEmailValidation = (email) => {
if (!email || email.length === 0) {
return 'Email cannot be empty';
}
const isEmailValid = /#/.test(email); // use any validator you want
if (!isEmailValid) {
return 'Invalid email provided';
}
return null;
};
Also it is a good practice to show validation message only after field was focused before and after user tried to submit the form.
Formik is a great plugin that will help you perform form validation. The examples are also quite clear.
Or you could do something like this:
const Login = () => {
const [error, setError] = useState(null);
const [state, setState] = useState({
email: '',
password: '',
});
const validateEmail = (email) => {
const re =
/^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
};
const handleChange = (e) => {
const { id, value } = e.target;
setState((prevState) => ({
...prevState,
[id]: value,
}));
};
const handleSubmitClick = (e) => {
e.preventDefault();
if (!validateEmail(state.email)) {
setError('Invalid Email');
}
if (state.password.length < 8) {
setError('Password must be at least 8 chars long');
}
if (!error) {
// No errors.
}
};
return (
<>
<div className='container'>
<div className='title'>
{error && <div style={{ color: 'red' }}>{error}</div>}
<form onSubmit={handleSubmitClick}>
<div className='form-group'>
<input
type='email'
className='email'
placeholder='Email'
value={state.email}
onChange={handleChange}
/>
</div>
<div className='form-group'>
<input
type='password'
className='password'
placeholder='Password'
value={state.password}
onChange={handleChange}
/>
</div>
<button type='submit' className='button'>
Enter
</button>
</form>
</div>
</div>
</>
);
};
export default Login;
For an empty validation you can check it preventing the submit if the field is empty, like
const handleSubmitClick = (e) => {
e.preventDefault();
if(email.trim() === '' || password.trim() === ''){
//Add a h1 or section with the error message
}else{
console.log("Authenticated",state);
}
}
As long as the email field type is equal to email, which is your case, the browser should give an alert if the string is not an email. ("user#example.com")

Form values coming as blank on submit

Not able to pick the values of email and token from the below form. It is displaying as blank during on click on submit. Can anyone please advise where I am doing wrong ?
https://codesandbox.io/s/dazzling-kirch-1gqq4?file=/src/App.js
import React, { useRef, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import Axios from "axios";
const CreateLink = () => {
const [email, setEmail] = useState("");
const [token, setToken] = useState("");
const {
handleSubmit,
register,
formState: { errors }
} = useForm();
const onSubmit = (e) => {
e.preventDefault();
alert(`Sending Email ${email}`);
const fetchData = async () => {
try {
const res = await Axios.post(
"http://localhost:8000/service/createlink",
email,
token
);
if (res.data.success) {
console.log("Link token created:" + res.data.success);
}
} catch (e) {
console.log(e);
}
};
fetchData();
};
return (
<div className="App">
<h1>Create Link</h1>
<form onSubmit={handleSubmit(onSubmit)} className="linkForm inputForm">
<div className="inputField">
<input
name="email"
placeholder="email"
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
{...register("email", {
required: "Email is required",
pattern: {
value: /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
message: "Invalid email address"
}
})}
/>
<span className="loginErrorTextFormat">
{errors.email && <p>{errors.email.message}</p>}
</span>
</div>
<div className="inputField">
<input
placeholder="token"
name="token"
type="text"
value={token}
onChange={(e) => setToken(e.target.value)}
{...register("token", {
required: "Token is required"
})}
/>
<span className="loginErrorTextFormat">
{errors.token && <p>Input is not valid</p>}
</span>
</div>
<input type="submit" />
</form>
</div>
);
};
export default CreateLink;
Because register return an object has property onChange. So it override your onChange, you just need move onChange after register
{...register("token", {
required: "Token is required"
})}
onChange={(e) => setToken(e.target.value)}

React hooks form doesn't reset the text fields even after submitting the data

React hooks form doesn't reset the text fields even after submitting the data to server. I have called setRegister({...initialState}); but it doesn't care and not resetting the fields, can someone please advise what could be the reason ?
const [formRegister, setRegister] = useState({ _id: "", nomineename: "", email: "", description: "", nominatedby: ""});
const onChange = (e) => {
e.persist();
setRegister({ ...formRegister, [e.target.name]: e.target.value });
}
const initialState = {
_id:"",
nomineename: "",
email: "",
description: "",
nominatedby: ""
};
const onSubmit = () => {
const fetchData = async () => {
try {
const res = await Axios.post('http://localhost:8000/service/nominateperson', formRegister);
if (res.data) {
console.log("Link token created:" + res.data);
const successMessage = res.data.message;
setHelperText(successMessage);
setRegister({...initialState});
}
} catch (e) {
console.log(e);
history.push('/errorPage');
}
}
fetchData();
}
return (
<div className="App">
<h1>Nominate Person</h1>
<form onSubmit={handleSubmit(onSubmit)} className="linkForm inputForm" >
<div className="inputField" >
<input name="nomineename"
placeholder="nominate a person"
type="text"
{...register('nomineename',{
required: "Nominate a person is required !",
pattern: {
value: /^[a-zA-Z\s]/,
message: "Invalid name !"
}
})
}
onChange={onChange}
/>
</div>
<span className="nominateError"><pre>{errors.nomineename && errors.nomineename.message}</pre></span>
<div className="inputField" >
<input name="email"
placeholder="nominee email"
type="text"
{...register('email',{
required: "Nominee email is required !",
pattern: {
value: /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
message: "Invalid email address !"
}
})}
onChange={onChange}
/>
</div>
<span className="nominateError"><pre>{errors.email && errors.email.message}</pre></span>
<div className="inputField" >
<textarea name="description"
placeholder="reason for nomination"
{...register('description',{
required: "Description is required !",
pattern: {
value: /^[a-zA-Z,.!""\s]{10,1000}$/,
message: "Min of 10 or not more than 1000 characters !"
}
})}
onChange={onChange}
/>
</div>
<span className="nominateError"><pre>{errors.description && errors.description.message }</pre></span>
<div className="inputField nominatedby" >
<input name="nominatedby"
placeholder="nominated by"
type="text"
{...register('nominatedby',{
required: "Nominated by is required !",
pattern: {
value: /^[a-zA-Z\s]{2,30}$/,
message: "Invalid name !"
}
})}
onChange={onChange}
/>
</div>
<span className="nominateError"><pre>{errors.nominatedby && errors.nominatedby.message}</pre></span>
<span className="getlinkbutton">
<input type="submit"/>
</span><br></br><br></br>
<label>
<span className="loginValidationText">{helperText}</span>
</label>
</form>
</div>
)
https://codesandbox.io/s/xenodochial-tereshkova-51t97?file=/src/App.js
The form state is controlled by useForm and not by your formRegister state.
Therefore, to reset form fields/state, you need to use its reset API.
const { reset } = useForm();
const onSubmit = () => {
reset(initialState);
const fetchData = async () => {
try {
...
if (res.data) {
...
reset(initialState);
setRegister({ ...initialState });
}
} catch (e) {
...
}
};
fetchData();
};

Is it possible Preload a form with Firestore values?

I have a form that uploads its values to the Firestore database, and would like to use the same component for updating the values, so the question might really be - how to load initial state according to a conditional whether the props are passed?
The form
import Servis from "./funkc/servisni";
import React, { useState } from "react";
export default function ContactUpdate(props) {
//
console.log(props.item);
//
const initialState = {
id: props.item.id,
ime: props.item.Ime,
prezime: props.item.Prezime,
imeError: "",
prezimeError: "",
date: props.item.Datum,
kontakt: props.item.Kontakt,
kontaktError: "",
published: true,
};
const [theItem, setTheItem] = useState(initialState);
const [imeError, setImeError] = useState();
const [prezimeError, setPrezimeError] = useState();
const [message, setMessage] = useState();
const { item } = props;
if (theItem.id !== item.id) {
setTheItem(item);
}
const handleInputChange = (event) => {
const { name, value } = event.target;
setTheItem({ ...theItem, [name]: value });
};
const updatePublished = (status) => {
Servis.update(theItem.id0, { published: status })
.then(() => {
setTheItem({ ...theItem, published: status });
setMessage("The status was updated successfully!");
})
.catch((e) => {
console.log(e);
});
};
const updateItem = () => {
let data = {
Ime: theItem.ime,
Prezime: theItem.prezime,
Kontakt: theItem.kontakt,
Datum: theItem.date,
published: true,
};
Servis.update(theItem.id, data)
.then(() => {
setMessage("The tutorial was updated successfully!");
})
.catch((e) => {
console.log(e);
});
};
const deleteItem = () => {
Servis.remove(theItem.id)
.then(() => {
props.refreshList();
})
.catch((e) => {
console.log(e);
});
};
const validate = () => {
let imeError = "";
let kontaktError = "";
if (!theItem.ime) {
imeError = "obavezan unos imena!";
}
if (!theItem.kontakt) {
imeError = "obavezan unos kontakta!";
}
if (kontaktError || imeError) {
this.setState({ kontaktError, imeError });
return false;
}
return true;
};
return (
<div className="container">
{theItem ? (
<div className="edit-form">
<h4>Kontakt</h4>
<form>
<div className="form-group">
<label htmlFor="ime">Ime</label>
<input
type="text"
className="form-control"
// id="title"
name="ime"
value={theItem.Ime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Prezime">Prezime</label>
<input
type="text"
className="form-control"
// id="description"
name="Prezime"
value={theItem.Prezime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Datum">Datum</label>
<input
type="text"
className="form-control"
// id="description"
name="Datum"
value={theItem.Datum}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Kontakt">Kontakt</label>
<input
type="text"
className="form-control"
// id="description"
name="Kontakt"
value={theItem.Kontakt}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
{theItem.published ? "Published" : "Pending"}
</div>
</form>
{theItem.published ? (
<button onClick={() => updatePublished(false)}>UnPublish</button>
) : (
<button onClick={() => updatePublished(true)}>Publish</button>
)}
<button onClick={deleteItem}>Delete</button>
<button type="submit" onClick={updateItem}>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Please click on a Tutorial...</p>
</div>
)}{" "}
</div>
);
}
The component passing the props:
import React, { useState, useEffect } from "react";
import firebase from "./firebase";
import { Link } from "react-router-dom";
export default function FireDetail({ match }) {
console.log(match);
console.log(match.params.id);
const [item, setItem] = useState([]);
const [loading, setLoading] = useState();
const getIt = () => {
setLoading(true);
const docRef = firebase
.firestore()
.collection("polja")
.doc(match.params.id)
.get()
.then((doc) => {
setItem(doc.data());
});
//
console.log(docRef);
//
// const docRef = firebase.firestore().collection("polja").doc("documentId")
//
setLoading(false);
};
useEffect(() => {
getIt();
}, [match]);
if (loading) {
return <h3>samo malo...</h3>;
}
return (
<div className="container">
<div>
{console.log("item: ", item)}
Kontakt: tip - email
<p> {item.Kontakt}</p>
</div>
<div>
<p>Datum rodjenja: {item.Datum}</p>
{item.Prezime} {item.Ime}
</div>
<Link to={`/kontakt/update/${item.id}`}> ajd </Link>
</div>
);
}
Or you might have an alternative idea on how to solve the problem?
indeed it is
export default function ContactUpdate(props) {
const initialState = {
ime: props.item.Ime,
prezime: props.item.Prezime,
datum: props.item.Datum,
kontakt: props.item.Kontakt,
id: props.Id,
};
const [theItem, setTheItem] = useState();
const [message, setMessage] = useState();
useEffect(() => {
setTheItem(props.item);
}, []);
const handleInputChange = (event) => {
const { name, value } = event.target;
setTheItem({ ...theItem, [name]: value });
console.log(theItem);
};
const updateItem = (theItem) => {
let data = {
Ime: theItem.Ime,
Prezime: theItem.Prezime,
Kontakt: theItem.Kontakt,
Datum: theItem.Datum,
};
console.log(updateItem());
Servis.update(theItem.id, data)
.then(() => {
setMessage("Uspjesno ste izmijenili unos!");
})
.catch((e) => {
console.log(e);
});
};
const deleteItem = () => {
Servis.remove(theItem.id).catch((e) => {
console.log(e);
});
};
return (
<div className="container">
{console.log(("theItem", props, theItem))}
{theItem ? (
<div className="edit-form">
<h4>Kontakt</h4>
<form>
<div className="form-group">
<label htmlFor="ime">Ime</label>
<input
type="text"
className="form-control"
name="Ime"
value={theItem.Ime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="prezime">Prezime</label>
<input
type="text"
className="form-control"
name="Prezime"
value={theItem.Prezime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="datum">Datum</label>
<input
type="text"
className="form-control"
name="Datum"
value={theItem.Datum}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="kontakt">Kontakt</label>
<input
type="text"
className="form-control"
name="Kontakt"
value={theItem.Kontakt}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
</div>
</form>
<button onClick={deleteItem}>Delete</button>
<button type="submit" onClick={updateItem}>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Odaberi jedan broj...</p>
</div>
)}{" "}
</div>
);
}

Resources