I want to call my API every 20 seconds from the moment where the component is rendered and the api calling has to stop when it provides a specific response.
Explaining more. There is an API get method which will send a response like below. {firstWork : ‘Success’ , SecondWork : ‘Success’ , ThirdWork : ‘IN-Progress’}
So I want to call this API periodically/repeatedly(every 20sec) from the point where the Component is Rendered and till all these becomes ‘Success’. {firstWork : ‘Success’ , SecondWork : ‘Success’ , ThirdWork : ‘Success’}
When I get the above response I should Stop calling the API get method. How can I achieve it in ReactJS?
Advertisement
Answer
You can achieve that by setting a setInterval
inside your component.
JavaScript
x
18
18
1
import { useEffect } from "react"
2
3
const Component = () => {
4
useEffect(() => {
5
const interval = setInterval(() => {
6
fetch("/yourApiEndpoint")
7
.then(res => res.json())
8
.then(json => {
9
if(json.thirdWork === "Success"){
10
clearInterval(interval)
11
}
12
})
13
}, 20*1000)
14
},[])
15
16
return <p>component</p>
17
}
18