TanStackT
TanStack3mo ago
16 replies
ill-bronze

How to conditionally call useLiveQuery

I have the following code:

const useElectricChatsByReportId = (reportId: string | null) => {
    const org = useCurrentOrg();
    const data = useLiveQuery(
        (q) =>
            q
                .from({
                    chats: chatsCollection
                })
                // Don't want to filter by null since that will match a bunch of chats
                .where(({ chats }) => eq(chats.reportId, reportId ?? 'undefined')),
        [org.id, reportId],
    );

    return data.data;
};


Ideally, I don't even want to run the live query if reportId is null. How can I do this withough violating the rules of react hooks? i.e. I can't do this since it would mean conditionally calling a hook:

const useElectricChatsByReportId = (reportId: string | null) => {
    if (!reportId) return [];
    const org = useCurrentOrg();
    const data = useLiveQuery(
        (q) =>
            q
                .from({
                    chats: chatCollection,
                })
                // Don't want to filter by null since that will match a bunch of chats
                .where(({ chats }) => eq(chats.reportId, reportId ?? 'undefined')),
        [org.id, reportId],
    );

    return data.data;
};
Was this page helpful?