redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

API for Dependent Queries

Open EskiMojo14 opened this issue 10 months ago • 1 comments

An issue that comes up regularly is building queries that want to pull data from other queries: #4828 #1171 to name a few

These queries would need to:

  • be provided the data from the dependent queries
  • rerun if any of those dependent queries refetch
  • act as a subscription for those queries (so their cache sticks around), unsubscribing when its own cache entry is removed

API still TBC, but some ideas raised in maintainers' chat:

build.query({
  query(arg, dependencies) {
    return `foo/${dependencies.first.id}`
  },
  dependencies(arg){
    return {
      first: { endpoint: "ep1", args: arg.foo }
    }
  }
})
build.withDependencies(
  (arg)=> {
    return {
      first: { endpoint: "ep1", args: arg.foo }
    }
  }
  ).query({
  query(arg, dependencies) {
    return `foo/${dependencies.first.id}`
  }
})
build.withDependencies(
  (arg)=> {
    return {
      first: api.endpoints.ep1.createDep(arg.foo)
    }
  }
  ).query({
  query(arg, dependencies) {
    return `foo/${dependencies.first.id}`
  }
})
async queryFn(postId, { dependentQuery }) {
  const comments = await dependentQuery("getComments", postId);

  const commentMetadata = await Promise.all(
    comments.map((comment) => dependentQuery("getCommentMetadata", comment.id)),
  );

  return { data: commentMetadata };
}
async queryFn(arg, api, extraOptions, fetchWithBq) {
  const first = await api.dependentQuery("ep1", arg.foo);
  if (first.error) return first;
  return fetchWithBq(`foo/${first.data.id}`);
}

EskiMojo14 avatar Jan 23 '25 18:01 EskiMojo14

Thoughts:

  • dependentQuery would be auto-dispatched because this is happening from within our thunk in the first place, so we've got dispatch available
  • we'd have to nest subscription behavior, ie "this subscription was triggered by a dependent query - when the dep query cache entry goes away, remove that subscription", and "if the dependent query changes, rerun this query too just in case"

markerikson avatar Jan 23 '25 18:01 markerikson