TelegramPWA/src/hooks/useEnsureStory.ts
2023-10-10 13:39:48 +02:00

33 lines
888 B
TypeScript

import { useEffect, useMemo } from '../lib/teact/teact';
import { getActions } from '../global';
import type { ApiTypeStory } from '../api/types';
import { throttle } from '../util/schedulers';
const THROTTLE_THRESHOLD_MS = 200;
function useEnsureStory(
peerId?: string,
storyId?: number,
story?: ApiTypeStory,
) {
const { loadPeerStoriesByIds } = getActions();
const loadStoryThrottled = useMemo(() => {
const throttled = throttle(loadPeerStoriesByIds, THROTTLE_THRESHOLD_MS, true);
return () => {
throttled({ peerId: peerId!, storyIds: [storyId!] });
};
}, [storyId, peerId]);
useEffect(() => {
const shouldLoadStory = !story || !('content' in story || 'isDeleted' in story);
if (peerId && storyId && shouldLoadStory) {
loadStoryThrottled();
}
}, [loadStoryThrottled, story, storyId, peerId]);
}
export default useEnsureStory;