Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
reactjs not updating state when needed

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. 
    }

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!