0
  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)

Mulan
  • 129,518
  • 31
  • 228
  • 259

2 Answers2

0

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;
Mayur Vaghasiya
  • 1,383
  • 2
  • 12
  • 24
  • you need to `clearInterval` when the component unmounts. you can do this by returning a thunk, `() => { ... }` from `useEffect`. See [Effects with cleanup](https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup) in the docs – Mulan Jan 05 '22 at 17:08
0

The (currently) accepted answer misses an important detail. When the component unmounts, the interval will keep running. To stop it, you need to clearInterval. Another mistake is useEffect is called without dependencies. Here we use useCallback to generate a function that will only update when the id updates. Both the callback and the id are passed as dependencies to useEffect -

const [data, setData] = useState(...)

const update = useCallback(id =>
  fetch(`http://.../${id}/`)
    .then(r => r.json())
    .then(setData),
  [id]
)

useEffect(() => {
  const t = setInterval(_ => update(id), 5000)
  return () => clearInterval(t)
}, [update, id])

In a related Q&A we introduce a custom useInterval hook that makes it easy for components to work with interval-based state. See the post for a fully functioning code demonstration.

Mulan
  • 129,518
  • 31
  • 228
  • 259