Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
tiagoevanp committed Jan 21, 2025
1 parent 6bddcc9 commit 5804fde
Showing 1 changed file with 18 additions and 26 deletions.
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
import type { QueriesResults } from '@tanstack/react-query';
import { keepPreviousData, useQueries } from '@tanstack/react-query';
import { useEffect, useState } from 'react';

import { useEnablePopupPreview } from './useEnablePopupPreview';
import { slashCommands } from '../../../../../app/utils/client/slashCommand';
import type { ComposerPopupOption } from '../../contexts/ComposerPopupContext';

export const useComposerBoxPopupQueries = <T extends { _id: string; sort?: number }>(filter: unknown, popup?: ComposerPopupOption<T>) => {
const [counter, setCounter] = useState(0);

useEffect(() => {
setCounter(0);
}, [popup, filter]);

const shouldPopupPreview = useEnablePopupPreview(filter, popup);

const enableQuery =
Expand All @@ -22,28 +15,27 @@ export const useComposerBoxPopupQueries = <T extends { _id: string; sort?: numbe
slashCommands.commands[(filter as any)?.cmd].providesPreview) ||
shouldPopupPreview;

const fetchData = async (source: 'local' | 'server') => {
if (source === 'local' && popup?.getItemsFromLocal) {
return popup.getItemsFromLocal(filter);
}

if (source === 'server' && popup?.getItemsFromServer) {
return popup.getItemsFromServer(filter);
}

return [];
};

return {
queries: useQueries({
queries: [
popup?.getItemsFromLocal && {
placeholderData: keepPreviousData,
queryKey: ['message-popup', 'local', filter, popup],
queryFn: () => popup?.getItemsFromLocal && popup.getItemsFromLocal(filter),
onSuccess: (args: T[]) => {
if (args.length < 5) {
setCounter(1);
}
},
enabled: enableQuery,
},
popup?.getItemsFromServer && {
placeholderData: keepPreviousData,
queryKey: ['message-popup', 'server', filter, popup],
queryFn: () => popup?.getItemsFromServer && popup.getItemsFromServer(filter),
enabled: counter > 0,
},
].filter(Boolean) as any,
queries: (['local', 'server'] as const).map((source) => ({
queryKey: ['message-popup', source, filter, popup],
queryFn: () => fetchData(source),
enabled: enableQuery,
})),
}) as QueriesResults<T[]>,
suspended: !enableQuery,
placeholderData: keepPreviousData,
};
};

0 comments on commit 5804fde

Please sign in to comment.