docz icon indicating copy to clipboard operation
docz copied to clipboard

Props of React Hooks components

Open BowenZ opened this issue 3 years ago • 0 comments

Hi, first of all, I'm not very good at English, so please don't mind if my grammar is weird 😁

I'm trying to write some React hooks components with TypeScript like react-use. And when I use <Props of={MyReactHookComponet}/> in mdx file, I found that it didn't generate any props.

All I can find is using import { Props } from 'gatsby-theme-docz/src/components/Props/' and write props document by myself.

Will you consider supporting generate props of hooks component?

Or is there a better way for this?

Thanks for your great job ♪(・ω・)ノ


Here is my code:

useCountdown.ts:

import { useState, useEffect, useRef, useCallback } from 'react';

type CountdownParams = {
  timer: number;
  interval?: number;
  autostart?: boolean;
  onTimeup?: () => void;
};

type CountdownResults = {
  countdown: number;
  isRunning: boolean;
  start(): void;
  pause(): void;
  set(value: number): void;
  reset(): void;
};

export default function useCountdown({
  timer,
  interval = 1000,
  autostart = false,
  onTimeup,
}: CountdownParams): CountdownResults {
  const [countdown, setCountdown] = useState(timer);
  const [isRunning, setIsRunning] = useState(autostart);
  const tickTimer = useRef<number | null>();

  const start = useCallback((): void => {
    console.log('====start====');
    setIsRunning(true);
  }, []);

  const pause = useCallback((): void => {
    console.log('====pause====');
    if (tickTimer.current) {
      clearInterval(tickTimer.current);
      tickTimer.current = null;
      setIsRunning(false);
    }
  }, []);

  const reset = useCallback((): void => {
    console.log('====reset====');
    setCountdown(timer);
  }, [timer]);

  const set = useCallback((value: number): void => {
    setCountdown(value);
  }, []);

  useEffect(() => {
    if (isRunning && !tickTimer.current) {
      const intervalId = setInterval((): void => {
        setCountdown((prev) => prev - 1);
      }, interval);
      tickTimer.current = intervalId;
    }
  }, [interval, isRunning]);

  useEffect(() => {
    if (countdown === 0 && isRunning && tickTimer.current) {
      clearInterval(tickTimer.current);
      tickTimer.current = null;
      setIsRunning(false);
      if (onTimeup) {
        onTimeup();
      }
    }
  }, [countdown, isRunning, onTimeup]);

  useEffect(() => {
    return (): void => {
      pause();
    };
  }, [pause]);

  return {
    countdown,
    isRunning,
    start,
    pause,
    set,
    reset,
  };
}

BowenZ avatar Aug 21 '20 07:08 BowenZ