'How to fix my onFormSubmit function with state?
There is part of my Component:
const { id } = useParams();
const [name, inputName] = useState("");
const [email, inputEmail] = useState("");
const [start, inputStart] = useState("");
const [end, inputEnd] = useState("");
const [errorNameEmpty, isErrorNameEmpty] = useState(false);
const [errorEmailValid, iserrorEmailValid] = useState(false);
const [errorStartEmpty, isErrorStartEmpty] = useState(false);
const [errorEndEmpty, isErrorEndEmpty] = useState(false);
const [errorDate, isErrorDate] = useState(false);
const [sendData, setSendData] = useState(false);
const validEmail = new RegExp(/^\S+@\S+\.\S+$/);
const onFormSubmit = (e) => {
e.preventDefault();
let startDate = new Date(start).getTime();
let endDate = new Date(end).getTime();
if (startDate > endDate || startDate === endDate) {
isErrorDate(true);
} else {
isErrorDate(false);
}
if (name === "") {
isErrorNameEmpty(true);
} else {
isErrorNameEmpty(false);
}
if (email === "") {
iserrorEmailValid(true);
} else if (!validEmail.test(email)) {
iserrorEmailValid(true);
} else {
iserrorEmailValid(false);
}
if (start === "") {
isErrorStartEmpty(true);
} else {
isErrorStartEmpty(false);
}
if (end === "") {
isErrorEndEmpty(true);
} else {
isErrorEndEmpty(false);
}
if (
errorNameEmpty ||
errorEmailValid ||
errorStartEmpty ||
errorEndEmpty ||
errorDate ||
sendData
) {
setSendData(false);
console.log("Net");
} else {
setSendData(true);
console.log("Da");
}
let newIntern = {
name: name,
email: email,
internshipStart: start + "T00:00+00Z",
internshipEnd: end + "T00:00+00Z",
};
if (sendData) {
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newIntern),
};
fetch(`http://localhost:3001/interns/${id}`, requestOptions).then(
(response) => response.json()
);
console.log("Good");
} else {
}
};
onFormSubmit is a function that fires when the button is clicked. I want that if there are no errors (that is, when all states that store error states = false) my fetch will work, and in the case when at least one state has an error = true then fetch will not be performed. Now after the first click, when I deliberately make a mistake in my form, the function works fine (fetch does not work), but immediately changes sendData = true. and if you click again, then fetch will work. I don't understand why sendData is set to true after the first call of the function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
