Quantcast
Viewing latest article 24
Browse Latest Browse All 56

Stateful custom hook

I have a component, StatusIndicator, that uses a Redux Toolkit query, q, to fetch a status value and display it.

I want to write a custom hook, usePolling, that can be configured using arguments to invoke q at intervals, updating StatusIndicator.

I have two problems:

  1. Even though I specify a dependency on isAuthenticated, the contents of the custom hook run repeatedly.
  2. How do I separate the state for each instance of the custom hook? I am using useState in an attempt to maintain the timeoutId for each instance. Is this correct?
export const StatusIndicator = () => {  const isAuthenticated = useSelector((state) => state.auth.token);  const { data, q } = useGetStatusQuery();  usePolling({ callback: q }, [isAuthenticated]);  return (<div>{{data.status}}</div>);};export const usePolling = ({ callback }, dependencies = []) => {  const [instanceTimeoutId, setInstanceTimeoutId] = useState(null);  // I only want this run when `isAuthenticated` changes  useEffect(() => {    (async function continuation() {      clearTimeout(instanceTimeoutId);      await callback();      const { timeoutId, promise } = delay(interval);      setInstanceTimeoutId(timeoutId);      await promise;      continuation();    })();    return () => clearTimeout(instanceTimeoutId);  }, [...dependencies]);};

Viewing latest article 24
Browse Latest Browse All 56

Trending Articles