Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda