React Router Redirect and useEffect memory leak

Viewed 332

I have a memory leak and I can't figure out what is causing it. I have a /login page that routes to / when successfull login. Then I have a Reroute after n seconds back to login page. Meanwhile I have an Axios get request on the / page. Everything looks fine until you open the console and realize there is a memory leak during the reroute. The login page appears but the console stays on the get requests and keeps requesting indefinitely. Here is some code...

const getData = React.useCallback(() => {
    const value = Axios.post("http://localhost:3001/api/get-value",
    {user: userProp}).then((response) => {
        const recievedData = response.data;
        const dataValue = recievedData.map((val) => {
            return [val.value]
        })
        if (loading === true){
            setLoading(false);
        }
        return parseInt(dataValue);
    }).then((resp) => {
        setMoisture(resp)
        return resp
    })
    return value
}, [userProp, loading])

try{
    const payload = usePolling(function () {
        return Promise.resolve(getData())
      }, 4000);
}catch(e){
    console.log(e)
}

the payload function...

function usePolling(fetcher, interval) {
const [payload, setPayload] = React.useState(null);

React.useEffect(function () {
  // you must implement the error handling
  fetcher()
    .then(function (resp) {
      setPayload(resp)
    })
}, [fetcher]);

React.useEffect(function () {
  let timeoutId;
  
  function poll() {
    timeoutId = setTimeout(function () {
      // you must implement the error handling
      fetcher()
        .then(function (resp) {
          setPayload(resp)
          poll();
        })
    }, interval);
  }
  poll()
  
  return function () {
    clearTimeout(timeoutId);
  }
}, [fetcher, interval]);

return payload;

}

and render...

if ((props.location.state) && timeDif <= .2) {
    return(
        <div className="App">
            <Switch>
            <Route path="/login" component={LoginComponent} />
            <Route path="/">
                <SensorComponent moisture={value} airValueObject={airValueObject}/>    
            </Route>
            </Switch>
        </div>
    );
}else{
    return(
        <div>
            <Route path="/login" component={LoginComponent} />
            <Route path="/">
                <Redirect to="/login" />
            </Route>
        </div>
    )
}

the memory leak is occuring in the getData function. My page has successfully redirected to the login but the console is still trying to run this function continuously.

0 Answers
Related