feat(query-core): pass mutation meta as optional second argument to mutationFn #9315
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Related discussion here. Below is copied from there:
I wanted to take a moment and make a case for making
meta
accessible inmutationFn
!In my mind, the
meta
field is a very convenient way to ensure access to shared context needed for all queries and/or mutations in an app. For example, in our web app, we have an API client which is instantiated once on load and then made accessible anywhere in the app through React Context. This is pretty convenient, but this API client is needed for every query or mutation we ever make that hits our API (which is 99% of them). So it is actually still pretty inconvenient that any time we ever want to useuseQuery
oruseMutation
, we also need to calluseApiClient
(our custom hook) to pass the API client into the query/mutation function.When I read the docs for the
meta
option, and how we can globally override the type, I thought it seemed like the perfect way to implement a lightweight wrapper arounduseQuery
anduseMutation
to always make the API client accessible in query/mutation functions by default. For example:Now instead of doing this every time we need to execute an API query:
We can simply do this:
Ideally, we wouldn't have to assert that
meta
is defined either, but the benefit here outweighs that easily. We have hundreds, and will eventually have thousands, of these API queries in our app. So having this available in thequeryFn
saves writing a remarkable amount of boilerplate.Much to my dismay, as I was implementing this, I realized that we do not get similar access to
meta
within themutationFn
used byuseMutation
. So we need to keep using the old pattern.I wonder then if it would be reasonable to add
meta
or a similar context containingmeta
as a second argument tomutationFn
. For us, it would be incredibly useful. I know that an authenticated API client accessible through context is a very common pattern in React apps, so I imagine this would be useful to others as well.Let me know what you think!