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

81
Views
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 answers
Answer question

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 Report

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 Report
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!