-
from this comment for v4: #1639 (comment)
While I aggree that the selection feature should be out of core, I think it is a good idea to provide it as an extra hook in react part of the react-query. I propose to add this hook: function useQuerySelector<TData = unknown, TError = unknown, TTargetData = unknown>(
queryResult: UseQueryResult<TData, TError>,
selector: (v: TData) => TTargetData,
deps: unknown[] = []
): UseQueryResult<TTargetData, TError> Usage will look like this (inspired by example in the issue #3065): function useTodosQuery() {
return useQuery("todos/all", loadTodos);
}
function useTodosCountQuery() {
const todosQuery = useTodosQuery();
return useQuerySelector(todosQuery, (todos) => todos.length);
}
function useTodoQuery(id) {
const todosQuery = useTodosQuery();
return useQuerySelector(todosQuery, (todos) => todos.find((t) => t.id === id), [id]);
} In my opinion, it makes it easier to reuse base query. with Thankfully to my poor googling skills (I did not found the https://codesandbox.io/s/usequeryselector-6divd1?file=/src/use-query-selector.ts In addition: I've been talking only about |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
We've iterated over selectors a lot of times since that comment, and there are currently no plans to remove them for v4. The issues mentioned in #1639 have been fixed. We now run select every time One very strong argument for the current architecture is partial subscriptions. For example:
Your proposal:
cannot do that because the observer will get informed about the updated todos via |
Beta Was this translation helpful? Give feedback.
-
Sorry if it's not good form to tack onto an exiting question. Why is function useTodosQuery() {
return useQuery("todos/all", loadTodos); // Returns UseQueryResult<Todo[]>
}
function useTodosCountQuery() {
return useTodosQuery().select(todos => todos.length); // Returns UseQueryResult<number>
} It would also empower calling components to perform context-specific transformations, and probably solve the type inference issues |
Beta Was this translation helpful? Give feedback.
We've iterated over selectors a lot of times since that comment, and there are currently no plans to remove them for v4. The issues mentioned in #1639 have been fixed. We now run select every time
data
changes or the referential identity to select itself changes, which might be on every render if it's an inline function (which likely doesn't matter much), but it can be optimized viauseCallback
or by extracting it to a stable function reference. I've written about that here: React Query Data Transformations.One very strong argument for the current architecture is partial subscriptions. For example: