Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

2.0 KB
Raw Blame
import { useCallback, useEffect, useState } from 'react';
import type { Dispatch, SetStateAction } from 'react';
import { api } from '../../../services/api';
import type { AppContextValue } from '../../../context/AppContext';
import type { TrackedContentItem } from '@shared/types/domain.ts';

export type ShowToast = AppContextValue['showToast'];
export type SetTrackedItems = Dispatch<SetStateAction<TrackedContentItem[]>>;

export function useTrackedItems(showToast: ShowToast) {
  const [items, setItems] = useState<TrackedContentItem[]>([]);
  const [loading, setLoading] = useState(true);
  // a failed load is shown as a failure, never as "nothing tracked yet"
  const [error, setError] = useState<string | null>(null);
  const [refreshingIds, setRefreshingIds] = useState(() => new Set<string>());

  const load = useCallback(async () => {
    try {
      const data = await api.getTrackedContent();
      setItems(Array.isArray(data) ? data : []);
      setError(null);
    } catch (err) {
      setError(`Couldn't load tracked content. ${(err as Error).message}`);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { load(); }, [load]);

  const retry = useCallback(() => {
    setLoading(true);
    load();
  }, [load]);

  const replaceItem = (id: string, updated: TrackedContentItem) => setItems(prev => prev.map(item => (item.id === id ? updated : item)));

  const handleRefresh = async (id: string) => {
    setRefreshingIds(prev => new Set(prev).add(id));
    try {
      const updated = await api.refreshTrackedContent(id);
      replaceItem(id, updated);
      showToast(`Refreshed "${updated.title || updated.label || 'this item'}"`);
    } catch (err) {
      showToast(`Couldn't refresh this item. ${(err as Error).message}`, 'error');
    } finally {
      setRefreshingIds(prev => {
        const next = new Set(prev);
        next.delete(id);
        return next;
      });
    }
  };

  return { items, setItems, loading, error, retry, refreshingIds, replaceItem, handleRefresh };
}