TanStackT
TanStack11mo ago
5 replies
brilliant-lime

Non-undefined placeholderData types as possibly undefined

If my placeholderData function always returns a proper result (not undefined), then why is the resulting
data
property typed as T | undefined?

Consider the following example:

function useBook() {
  const bookId = useBookId();

  return useQuery({
    queryKey: ["book", bookId] as ["book", number],
    queryFn: ({queryKey: [, bookId]}) => fetchBook(bookId),
    placeholderData: (previousBook) => previousBook ?? {id: 123, title: "Default Book"},
  });
}

function useBookTitle() {
  const {data: book} = useBook();
  return book.title;
}


Shouldn't placeholderData always (synchronously, without loading) stand in for
data
while loading/fetching/intializing/etc?

If not, how can I achieve this? In other words, how can I seed this particular query observer with a known value?

(In practice, the above code does not error as far as I've tested. I also tried initialData, but that seems to override placeholderData with flashes back to the inital value -- I want the use-the-previous-thing behavior)
Was this page helpful?