1

I am using setInterval on react redux. Below is my function.

FileAction.js

export const SetPath = ({ path, location }) => async (dispatch) => {
    try {
        let interval;
        if (pre_path === path) {
            interval = setInterval(() => {
                handler(path);
            }, 3000);
        } else {
            pre_path = path;
            clearInterval(interval);
        }

        const handler = async (pth) => {
            const mtime = await axios.post('/api/file', { data: pth });
            dispatch({
                type: GET_EVENT,
                payload: { time: mtime, position: location }
            });
        }
    } catch (err) {
        dispatch({
            type: GET_ERROR
        });
    }
};

What I would like to do is when I call SetPath function, it have to fetch data from api/file every 3 secs.

But now when I pass another path to SetPath function, it dulicate interval.

How can I implement this?

Alchemist
  • 325
  • 1
  • 17
  • Does this answer your question? [How to fetch data automatically every minute in React?](https://stackoverflow.com/questions/59631152/how-to-fetch-data-automatically-every-minute-in-react) – Heretic Monkey Aug 18 '22 at 11:55
  • use a ref to store the interval since you need it to persist between renders – nullptr Aug 18 '22 at 11:58

1 Answers1

2

You are defining the interval variable inside setPath function, therefore the variable will be reinitialized everytime setPath is executed. Try defining it outside the function. You may need to use useRef in order to not lose the variable when a re-render occurs.

Zeno Dalla Valle
  • 957
  • 5
  • 16