Home > Enterprise >  Infinite Loop Based On State in React
Infinite Loop Based On State in React

Time:09-21

I would like to toggle infinite loop inside my React component with Redux state. This is what I've got until now but it does not work correctly because it does not stop when the state is changed because the function uses the old version of it.

const { monitors } = useSelector((state) => state.monitors)

useEffect(() => {
    handleMonitoring(monitors)
}, [monitors])

const handleMonitoring = async () => {
    if (monitors && monitors.filter(monitor => { return monitor.active }).length) {
        await dispatch(watchMonitors(monitors));
        return handleMonitoring()
    }
    else {
        console.log('closed')
        return;
    }
}

CodePudding user response:

I think using a recursive function instead of an infinite loop is better idea.

const handleMonitoring = async () => {
  await dispatch(watchMonitors(monitors));
  if(monitors && monitors.filter(monitor => { return monitor.active }).length) {
    return;
  }
  else {
    return handleMonitoring()
  }
}

CodePudding user response:

you must declare an additional variable to determine if you want to continue the monitoring.

This variable will be initialized to true and set to false in the cleanup function.

const { monitors } = useSelector(state => state.monitors)

useEffect(() => {
    let active = true;
    
    async function handleMonitoring() {
      while(active && monitors && monitors.find(m => m.active)) {
        await dispatch(watchMonitors(monitors));
      }
      console.log('closed');
    }

    handleMonitoring();

    return () => { active = false; };
}, [monitors]);
  • Related