TanStackT
TanStack9mo ago
9 replies
managerial-maroon

What is the correct way to subscribe to a fresh queryObserver?

I skimmed the source for query observer and useBaseQuery and it's not obvious why the naive solution here isn't okay if our goal is that handleResult get notifications for current state + all future updates:

export function safeSubscribeObserver<Obs extends QueryObserver<any, any, any, any, any>>(
  observer: Obs,
  handleResult: Parameters<Obs['subscribe']>[0]
): () => void {
  handleResult(observer.getCurrentResult());
  const unsub = observer.subscribe(handleResult);
  return unsub;
}


Vs what useBaseQuery seems to be doing:
export function safeSubscribeObserver<Obs extends QueryObserver<any, any, any, any, any>>(
  observer: Obs,
  handleResult: Parameters<Obs['subscribe']>[0]
): () => void {
  handleResult(observer.getOptimisticResult(options));
  const unsub = observer.subscribe(handleResult);
  observer.updateResult();
  return unsub;
}

Is the baseQuery implementation just working around react things or is it somehow more correct than the naive version?

Note i know for certain that the query observer was just created but I don't know about if refetchOnMount is true or if the query key is in the cache or not.

I also know the query key and options haven't changed.

Seems like the only risk is that #currentResult is undefined still but that seems impossible given my other assumptions and reading of the code.
Was this page helpful?