I have some input fields that must be set before calling onCompleteOrder. I store errors using useState, I need the program to keep looking at which fields are not set and therefore keep the error inside errors state. If errors state is not empty, then block calling that function. The problem is that the state is updated after the button is clicked, I know that this must be handled using the useEffect hook, how do I do that correctly?
const OrderModal = (props) => {
const [errors, setErrors] = React.useState([])
const [selectedFile, setSelectedFile] = React.useState(oldFile)
const [startDate, setStartDate] = React.useState(new Date());
const [endDate, setEndDate] = React.useState(null);
const { isAuthenticated, user } = useAuth0();
React.useEffect(() => {
let currentErrors = errors.map(err => err.type)
let newErrors = []
if (!isAuthenticated && currentErrors.includes("authentication")) newErrors.push({ type: "authentication", message: "You must log in before creating an order!." })
if (!selectedFile && currentErrors.includes("image")) newErrors.push({ type: "image", message: "Please select an image." })
if (!startDate && currentErrors.includes("startDate")) newErrors.push({ type: "startDate", message: "Please select a start date." })
if (!endDate && currentErrors.includes("endDate")) newErrors.push({ type: "endDate", message: "Please select an end date." })
setErrors(newErrors)
}, [isAuthenticated, selectedFile, startDate, endDate])
}
const renderInputErrors = () => {
return (
<>
{errors.length > 0 &&
errors.map(e => {
return (
<CAlert color="danger" dismissible>
{e}
</CAlert>
)
})
}
</>
)
}
const onCompleteOrder = () => {
if (errors.length > 0) return
// complete the order if all fields are set.
}