Search code examples
reactjsreact-hooksfunctional-programmingrenderintervals

how to render react functional component after interval


  useEffect(() => {
    const url = `https://......com/..../${id}`;
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        console.log(serviceDetail);
        setServiceDetail(data);
      });

Note: I want it to render it after a certain time like every 5 seconds.(more or less)


Solution

  • Try this code it's helps

    function App() {
      const [serviceDetail, setServiceDetail] = useState(0);
    
      const handleApiCall = () => {
        const url = 'https://......com/..../${id}';
        fetch(url).then((res) => res.json()).then((data) => {
          console.log(serviceDetail); setServiceDetail(data);
        });
      }
      useEffect(() => {
        handleApiCall(); //for call api init time 
       
       const interval = setInterval(() => {
          handleApiCall(); // call api after 5 seconds
        }, 5000);
    
        return () => clearInterval(interval); // clear interval after component unmounts.
      });
    
      return (
        <div>
    
        </div>
      );
    }
    export default App;