skip to Main Content

This is what I simply have in my file:

  const isInProgress = progress?.status === 'IN_PROGRESS' ?? false;
  useEffect(() => {
    const interval = setInterval(() => {
      if (isInProgress) {
        return setTime(Date.now());
      } else {
        return null;
      }
    }, 1000);
    return () => {
      clearInterval(interval);
    };
  }, [isInProgress]);

and now I would like to move it to another hook to utils file like this:

export const useRefreshProgress = (isInProgress: boolean) => {
  const [_, setTime] = useState(Date.now());
  const refreshProgress = useEffect(() => {
    const interval = setInterval(() => {
      if (isInProgress) {
        return setTime(Date.now());
      } else {
        return null;
      }
    }, 1000);
    return () => {
      clearInterval(interval);
    };
  }, [isInProgress]);
  return { refreshProgress };
};

and trying to use it like this:

  const { refreshProgress } = useRefreshProgress(isInProgress);
  refreshProgress(); // This expression is not callable. Type 'void' has no call signatures.

I just started learning react native and cannot solve it here;) Thank you for your help;)

2

Answers


  1. Don’t need to call refreshProgress. It will be called automatically by useEffect hook when calling useRefreshProgress.

    Login or Signup to reply.
  2. In addition to Jonas Beck’s answer, I would also refactor your hook further:

    1. Init the state with a function. See Avoiding recreating the initial state.
    2. In the useEffect bail out early before creating the interval if isInProgress is false.
    3. Return the time state, because it might be usable.

    Code:

    const getTime = () => Date.now();
    
    export const useRefreshProgress = (isInProgress: boolean) => {
      const [time, setTime] = useState(getTime); // lazy init
    
      const refreshProgress = useEffect(() => {
        if (!isInProgress) return () => {}; // skip if not in progress and return an empty cleanup
    
        const interval = setInterval(() => {
          setTime(getTime());
        }, 1000);
    
        return () => {
          clearInterval(interval);
        };
      }, [isInProgress]);
    
      return time; // return the time because it might be usable
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search