1

Is there a way to run a background process which would run a function every few minutes to call backend API and update the redux state. It is a large React App which has lot of components. This affects globally so I am looking for just a background process to do this.

I am looking if someone has done this before or used a ReactJS library to do it.

Learn AspNet
  • 1,192
  • 3
  • 34
  • 74
  • Tried using it via `setInterval`? Similar example: https://github.com/ccPrathap/sai-eog-react-assessment/blob/master/src/components/DroneVisualization.js#L19 – Prathap Reddy Aug 06 '20 at 13:43
  • @PrathapReddy Like I mentioned it is a big react component. What if the user is on a different page. Can you expand on your answer? – Learn AspNet Aug 06 '20 at 13:49
  • You can have all such calls in you main file like `App.js`. Will that be an issue in you case? – Prathap Reddy Aug 06 '20 at 13:50

2 Answers2

4

Create a component like BackgroundTask and put it in your page with a useEffect inside :

useEffect(() => {
  const timer = setInterval(() => {
    // call you action here
  }, 5000);
  return () => clearInterval(timer)
}, [])

And add it to the App component :

export default App => (
      <Provider store={store}>
        <BackgroundTask/>
        ... rest of your app ...
     </Provider>
);
0

You can achieve this by using setTimeout() function.

All you have to do is, inside your main root component, let's assume your root component is App.js. you can do the following.

import React, { useEffect } from 'react';

const App = () => {
  
  useEffect(() => {
    const timer = setTimeout(() => {
      /* Your API call */
    }, 1000);
    return () => clearTimeout(timer);
  }, []);

  return (
    <div>
      /* allYourComponents */
    </div>
  );
};

export default App;