BrainlaqB
tRPC11mo ago
1 reply
Brainlaq

Early return for certain input parameter for queryFn

I want to transform this useQuery to trpc

import { useSuspenseQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";

type ChatMessage = { text: string; userName: string };

type ChatHistory = Array<ChatMessage>;

export const useChatHistory = () => {
  const { id } = useParams<{ id: string | undefined }>();

  return useSuspenseQuery({
    queryKey: ["getChatHistory", id],
    queryFn: async () => {
      if (!id) return [];

      const result = await fetch("/api/chat-history/" + id);

      const data = await result.json();

      return data as ChatHistory;
    },
  });
};


i came up with this but although eslint does not complain this surely is against the rules of react / a bad pattern because I am calling a hook conditionaly, right?

import { trpc } from "@/lib/trpc/client";
import { useParams } from "next/navigation";

export const useChatHistory = () => {
  const { id } = useParams<{ id: string | undefined }>();

  if (!id) return [];
  const [chatHistory] = trpc.getChatHistory.useSuspenseQuery(id);

  return chatHistory;
};


I wrote this hook to get the chat history for existing chats while pasing an empty history to the mutation when creating a new chat. I understand this could be done server side but i want to prevent the unnecessary fetch.
Was this page helpful?