Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

83
Vistas
Run useEffect only on submit

I have this functional component -

    function ModelPredict({ model }) {
    const [predictionDate, setPredictionDate] = useState('')
    const [predictionValue, setPredictionValue] = useState('')
    const [isLoading, setIsLoading] = useState(false)

    useEffect(() => {
        const fetchPrediction = async () => {
            setIsLoading(true)
            const res = await fetch(`http://localhost:8000/api/predict/${model.id}/?`
                              + new URLSearchParams({pred_date: predictionDate}))
            const predictionValue = await res.json()
            setPredictionValue(predictionValue)
            setIsLoading(false)
        }

        if (predictionDate) fetchPrediction()
    }, [predictionDate, model])

    return (
        <div>
            <label>Select Prediction date: </label>
            <input type="date" name="date" value={predictionDate}
             onInput={e => setPredictionDate(e.target.value)} />
            <input type="submit" value="Submit"/>
            {isLoading && <p>Predicting ...</p>}
            {!isLoading && predictionValue && <p>Prediction: {predictionValue.prediction}</p>}
        </div >
    )
}

Currently useEffect will fire every time on date input.
I want that the useEffect should run only when the submit button is clicked.

One way to do it would be to have another state inpReady and calling setInpReady(true) inside onSubmit and then check inside useEffect if inpReady is true before calling fetchPrediction.
Is there a better way?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I don't know if I'm understanding your question, but what's the need for useEffect here? what's the problem with removing all the code from useEffect and putting it all inside your onSubmit function? that would solve your issue.

about 4 years ago · Juan Pablo Isaza Denunciar

0

One option can be setting a isSubmmited flag and use it as a dependency in the useEffect:

const [isSubmmited, setIsSubmitted] = useState(false)

And then onSubmit to call setIsSubmmited(true)

Another option is simply to let the onSubmit handle the logic you want in the useEffect

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda