Search code examples
javascriptreactjsrxjs

How to keep a reference to a timer in a function component


React has the useRef that allows me to hold onto a reference to an object. I'm trying to start a repeated call to an api using a timer. When the user clicks stop, I want to stop the repeated call, or "unsubscribe".

subscription = timer(0,1000).subscribe(n => dispatch(fetchData())); subscription.unsubscribe();

Those functions are from the rxjs library

Is there a way that I can do that in my function onSubmit() (which is inside a function component) using the useRef function of React to maintain a reference to subscription so that I can unsubscribe?

function onSubmit(){ 
    /// if 
     subscription = timer(0,1000).subscribe(n => dispatch(fetchData()));
    ///else 
     subscription.unsubscribe();

  } 
    

Solution

  • You can only use useRef() in a component or in a hook. You cannot use it just in a stand alone JS function.

    Assuming your onSubmit is defined inside a component then you could do something like:

    import { useRef } from 'react';
    
    // ...
    
    export const MyComponent = (props) => {
    
      const subscription = useRef(null);
    
      function onSubmit() { 
        if (subscription.current === null) {
         subscription.current = timer(0,1000).subscribe(n => dispatch(fetchData()));
        } else {
         subscription.current.unsubscribe();
         subscription.current = null;
        }
      }
    
      // ...
    };