Вот кусок моего компонента (без return):
import React, { useEffect, useState } from "react";
import { useParams } from "react-router";
import { NavLink } from "react-router-dom";
import "./styles/editIntern.sass";
const EditIntern = () => {
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();
isErrorDate(startDate > endDate || startDate === endDate);
isErrorNameEmpty(name === "");
isErrorEmailValid(email === "" || !validEmail.test(email));
isErrorStartEmpty(start === "");
isErrorEndEmpty(end === "");
if (
errorNameEmpty ||
errorEmailValid ||
errorStartEmpty ||
errorEndEmpty ||
errorDate
) {
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 {
}
};
useEffect(() => {
const fetchIntern = async () => {
const response = await fetch(`http://localhost:3001/interns/${id}`);
const intern = await response.json();
console.log(intern);
inputName(intern.name);
inputEmail(intern.email);
inputStart(intern.internshipStart.slice(0, 10));
inputEnd(intern.internshipEnd.slice(0, 10));
};
fetchIntern();
console.log(`I want to get intern with id: ${id}!`);
}, [id]);
return ...........
Почему
onFormSubmit не работает должным образом (
setSendData всегда
true независимо от условий выше)?
Такое чувство, что функция не видит изменений
useState у ошибок, и для последней проверки все ошибки всегда остаются
false).