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.
import { useEffect } from "react" const Component = () => { useEffect(() => { const interval = setInterval(() => { fetch("/yourApiEndpoint") .then(res => res.json()) .then(json => { if(json.thirdWork === "Success"){ clearInterval(interval) } }) }, 20*1000) },[]) return <p>component</p> }