Aniket Banyal
Aniket Banyal

Reputation: 452

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?

Upvotes: 1

Views: 2264

Answers (2)

DSCH
DSCH

Reputation: 2376

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

Upvotes: 0

e.a.
e.a.

Reputation: 948

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.

Upvotes: 2

Related Questions