Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom equality check for determining argument changes in useQuery from rtk-query/react #1768

Closed
kasper573 opened this issue Nov 25, 2021 · 3 comments

Comments

@kasper573
Copy link

kasper573 commented Nov 25, 2021

This issue is referring to how stableArg is determined in buildHooks.ts/useQuerySubscription:

const stableArg = useShallowStableValue(skip ? skipToken : arg)

The problem

In the examples below, useQuery is pseudo code to refer to an arbitrary query hook generated by @reduxjs/toolkit/query/react.

The current implementation performs a shallow equality check to allow the hook consumer to pass in inline objects without having to manually memoize these:

useQuery({foo: 123, bar: "baz"}) // This is stable

However, if the consumer wants to use a nested object, the shallow equality will not be able to understand that no change has been made:

useQuery({nested: {foo: 123, bar: "baz"}}); // This is not stable

To work around this the consumer would have to manually memoize the query argument, which easily becomes very verbose in larger projects with lots of queries and views, requiring an extra statement per query.

const stableArg = useMemo(() => ({nested: {foo: 123, bar: "baz"}}), []);
useQuery(stableArg);

Suggested solution

I suggest to provide the option to use any kind of equality checking:

useQuery({nested: {foo: 123, bar: "baz"}}, {equalsFn: deepEquals}); // This is stable

In the above example, useQuery would determine whether the argument has changed by calling the provided deepEquals function, instead of the default shallowEquals function.

Additionally, a central configuration could be provided, to modify the default equality checking function for all queries:

createApi({
  baseQuery: ...,
  endpoints: ...,
  useQueryArgEqualsFn: deepEquals
})
@kasper573 kasper573 changed the title Custom equality check for stableArg in useQuery from rtk-query/react Custom equality check for determining argument changes in useQuery from rtk-query/react Nov 25, 2021
@markerikson
Copy link
Collaborator

markerikson commented Nov 25, 2021

@kasper573
Copy link
Author

@markerikson You are absolutely right! I just tried the beta and it works exactly as I would like it to!

My bad, thanks a lot!

@markerikson
Copy link
Collaborator

no worries :) glad to hear it works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants