close
The Wayback Machine - https://web.archive.org/web/20201102175457/https://github.com/tannerlinsley/react-query/discussions/1246
Skip to content
💡 Ideas

v3: Remove auto-passing of query key variables to functions, replace with query context. #1246

💡 Ideas
1h ago
· 5 replies
1h

@tannerlinsley tannerlinsley
Maintainer

Instead of the API allowing/affording to automatically passing the query keys (spread into args) like this:

const fetchPostById = (_, _ , id) => {
  // ...
}
useQuery([userId, 'posts', id], fetchPostById)

// or

const fetchPosts = (userId, _, cursor) => {
  // ...
}
useInfiniteQuery([userId, 'posts'], fetchPosts, {
  getNextPageParam: (lastPage, pages) => lastPage.nextIndex
})

The function would simply be passed a context object, and we would update the documentation/educational material to first encourage passing an inline function, then expose users to the more powerful context-driven function parameter:

useQuery([userId, 'posts', id], () => fetchPostById(id))

// or

useInfiniteQuery([userId, 'posts'], (queryOrCtx) => {
  return fetchPosts({
    userId,
    cursor: queryOrCtx.nextPageParam
  })
}, {
  getNextPageParam: (lastPage, pages) => lastPage.nextIndex
})

Pros

  • No more encouragement of patterns that result in unused variables everywhere
  • Parameter count, argument types and function signature are now more predictable for both internals and users
  • With a single parameter, infinite query functions no longer have to list out all of the unused queries to get to the page parameter.
  • Relatively easy migration
  • If users still want to abstract into a function declaration, they can still do that:
const fetchPostById = ({ queryKey: [userId, , id] }) => axios.get(`/${userId}/posts/${queryOrCtx.id}`)
useQuery([userId, 'posts', id], fetchPostById)

Cons

  • Not backwards compatible

Replies

I like it. Having the query key passed in as first arguments was a bit confusing and not intuitive.

Agreed; I've just been creating inline functions per your example to avoid the un-used variables in my methods.

Nice, I was having the exact same problem to retrieve the cursor, and started a discussion here:
#1224

but then found an easier workaround where I put all the query params in an object, so I "only" had to exclude the first two parameters. It's still a bit annoying to get the cursor. It is also not type-safe, so with TS, we are using the inline functions all the time.

@tannerlinsley

tannerlinsley
Maintainer Author

Your discussion sparked this idea 😉

@tannerlinsley tannerlinsley
Maintainer Author

Judging from the additive discussion happening in Discord, this is a very good idea. @boschni Would this be difficult to implement in v3?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
4 participants
Beta
You can’t perform that action at this time.