I want the useEffect to happen only when the button "Analyze Weather" is clicked, how do i do that ?
This is my code
const PredictBestPage = () => {
const [latitude , setLatitiude] = useState('')
const [longitude , setLongitude] = useState('')
const [isAnalyzing , setIsAnalyzing] = useState(false)
const API_ENDPOINT = 'https://api.openweathermap.org/data/2.5/onecall?'
const API_KEY = //The Api Key(I cannot show this)
useEffect(() => {
navigator.geolocation.getCurrentPosition((postion) => {
setLatitiude(postion.coords.latitude)
setLongitude(postion.coords.longitude)
})
axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
.then((res) => {
console.log(res.data)
})
}, [])
const analyzeWeather = () => {
if(latitude === "" || longitude === "") {
<ErrorPrediction />
}
setIsAnalyzing(true)
}
return (
<>
<Navbar />
{
isAnalyzing
?
<div className = {styles.loader}>
<Loader />
</div>
:
<div className= {styles.predictMainCont}>
<div className= {styles.analyzeBtn} onClick= {analyzeWeather}>
Analyze Weather Conditions
</div>
</div>
}
</>
)
}
export default PredictBestPage
So basically i want it that when i click the Analyze Weather button which has the onclick of function analyzeWeather the useEffect should fire off. How do i do that? I am a beginner at this, thank you for the assist in advance.
CodePudding user response:
Add your useState variable in the useEffect
useEffect(() => {
navigator.geolocation.getCurrentPosition((postion) => {
setLatitiude(postion.coords.latitude)
setLongitude(postion.coords.longitude)
})
axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
.then((res) => {
console.log(res.data)
})
}, [isAnalyzing])
Adding isAnalyzing
in the UseEffect will run the code when you click the button.
CodePudding user response:
Your current useEffect will works just one time which is after mounting your component. If you want to run it again with changing of isAnalyzing state, you must add it to dependency array of useEffect
useEffect(() => {
// Callback function
}, [dependency array])
So, your useEffect hook must be :
useEffect(() => {
navigator.geolocation.getCurrentPosition((postion) => {
setLatitiude(postion.coords.latitude)
setLongitude(postion.coords.longitude)
})
axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
.then((res) => {
console.log(res.data)
})
}, [isAnalyzing])
But, There is an important fact: Your useEffect will be invoked once withouth any click.
If you don't want this, You can simply use a regular function to call data with api. It depends on your buisiness logic.