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
refetchQueries not working when using string array after mutation #5419
Comments
I had a similar problem but was resolved by providing the exact object used to fetch the query which may include any variables, query options and etc. |
The whole purpose of using a string is that you should NOT have to provide the exact object as Apollo should automatically refetch the query with the current query variables. |
Yeah I totally agree with you there man it sure is a bug or documentation is wrong. Didn't mean to sound like it ain't a bug. It's very inconvenient having to provide the exact same object especially multiple mutations in multiple places refetches the query. |
I have a similar issue. The weird thing is that when I call a mutation where it deletes a row, and then I call the refetchQueries with a string, it actually works. But after I insert a new row, nothing happens when I do the refetch. It makes no sense because the delete is still a mutation, so I'm not sure what the difference could be. Both mutations return the same values. I'm looking at the network requests, and I see that after the insert there is no request, but after the delete, there is a new request that actually do re fetch The only way I could make this to work is to change the fetch policy to |
I have witnessed exactly the same behaviour! It works fine when I refetch after I delete an item but not when I create one. |
Hi Friends, I have the same problem: refetchQueries works with update mutations, but nothing happens on insert mutations. Is there any known workaround? |
Impacting us here also... 😫 |
Also running into this issue |
I came accros this issue. If I cancel the redirect, which comes right after the mutation, there is no problem. After the query is refetched, cache gets updated. I think, when the page that observes the query gets unmounted, even if the network request gets completed, cache can not be updated. A cool way could be invalidating a query even if it wasn't observed by any active component. This is just a simple idea of course. There may be positive/negative points about this. Edit: After some thinking, I feel like using Most of the times I just don't feel it's ok to change the default |
In case anyone is still interested, this behavior happens because when you delete something, the component holding the original query didn't get unmounted (normally because you just show a popup), while when creating a new item you redirect to another screen (i.e. create item page) unmounting the page holding the original query. Apollo maintains a list of observable queries at any given time, which is based on which components are currently mounted that defined a query (i.e. through I don't know if @hwillson would like to give us more context as to whether there is a way around this (except from not using the React or by making sure that we unmount as little as possible on crucial refetches). In short:
|
So it's not possible to perform a refetch with the original query and variables? Doesn't sound to me a good choice :/ |
It's only possible if you don't navigate away (i.e. unmount the component that performed the original query). Your other option (which is not actually a solution) is to use a different |
I see; thanks! |
I have three components render on the same page which use the same query(and same operation name) but difference variables. |
cause it literally does just that. It refetches the query with the latest variables. From apollo's side it's only 1 query with 3 different invocations, so i tries to refetch the "latest" invocation. |
Still an issue in 3.1.5 on May 22nd 2020. |
What happened with this issue, please!! |
I think this needs to have option to refetch non observable queries. those flags can solve a lot of issues |
Apollo client 3.2.5 and issue is not fixed. Any updates? |
May be related to #3540 |
I have a very similar problem to the one you are experiencing here, I'm on version 3.3.11. |
@espinhogr got the same issue. In my case refetch was performed on a component that was already unmounted, and that - for some reason worked well on dev, but didn't on prod. Check your warnings (red ones lol), maybe that's the case for you as well. |
on the other side, |
Same here, working on dev but not on prod.... please help |
This is still an issue on 3.4.7 Reproduction: Navigate to 'Mutation' and click 'Mutate'. You'll see a console warning:
However as per the docs
it should work, as the query |
It is still an issue in It works for me if I have a query and a mutation in the same component/route, but it does not work if I call it in the component/route that does not have the query to be refetched.
|
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
I just came across this myself in I modified #5419 (comment) to get a intersected list of active query names. import { DocumentNode, useApolloClient } from "@apollo/client"
import { QueryInfo } from "@apollo/client/core/QueryInfo";
function intersect(a: string[], b: string[]) {
const setB = new Set(b);
return [...new Set(a)].filter(x => setB.has(x))
}
export function useGetActiveQueries(toRefetch: string[]) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const client = useApolloClient() as any; // any to get access to private props, 😬
const initialQueries = client.queryManager.queries as Map<string, QueryInfo>;
const queryDocuments: Record<string, {
query: DocumentNode | null
// eslint-disable-next-line @typescript-eslint/no-explicit-any
variables: Record<string, any> | undefined
}> = {}
const allQueries = initialQueries.values();
for (const queryDoc of allQueries) {
queryDocuments[queryDoc.queryId] = {
query: queryDoc.document,
variables: queryDoc.variables
}
}
return intersect(Object.values(queryDocuments).map(doc => {
const def = doc.query?.definitions[0]
if (def?.kind === 'OperationDefinition') {
return def.name?.value ?? ''
}
return ''
}).filter(name => name !== ''), toRefetch)
} Usage: // inside Component
const refetchQueries = useGetActiveQueries(["QueryFoo", "QueryBar"])
const [exec, { loading }] = useMutation(mutation, {
refetchQueries,
}) |
|
@amaster507 interesting solution! Feel free to keep using it, but I'd recommend a couple tweaks that is more safe (i.e. not subject to breaking changes) and doesn't require you to reach into the internals as much.
const initialQueries = client.queryManager.queries as Map<string, QueryInfo>; Use const activeQueries = client.getObservableQueries('active');
const queryDocuments = Array.from(activeQueries.values())
.map(observableQuery => observableQuery.query);
import { getMainDefinition } from '@apollo/client/utilities';
return intersect(Object.values(queryDocuments).map(doc => {
const def = getMainDefinition(doc.query);
if (def?.kind === 'OperationDefinition') {
return def.name?.value ?? ''
}
return ''
}).filter(name => name !== ''), toRefetch) @dizzyjaguar I'm curious, when you're seeing this issue, is the query you're trying to refetch an active query? It's possible its not refetched for that reason (in which case the helper by @amaster507 would help). If you'd like to refetch regardless of whether the query is active, consider passing the query document to your // where MY_QUERY is a query wrapped in `gql`
import { MY_QUERY } from './some/path';
mutate({
// ...
refetchQueries: [MY_QUERY]
}) If the query is active and you're still not able to refetch using a string array, we could use some help providing a reproduction where we can look at this a bit more in-depth. As @alessbell tried above this seems to be functioning as we the maintainers expect, but there could be something else that we just aren't seeing. A reproduction goes a long way to help us better diagnose the issue. Hope this helps! |
I said this earlier in the thread but I'll try to outline it again. I think the problem is one of ergonomics not functionality - as you say, "functioning as we the maintainers expect". When using the library, generally people just want to say "I now know that this data isn't valid so refetch it if I ask for it again". But what apollo-client expects of people is to say "I now know that this specific active query isn't valid so please refetch it now", which is a much less predictable thing and very hard for a developer to work with in the general case. For instance, it's very possible that a mutation will invalidate data in a way that I can predict, but that the queries that reference that data aren't particularly predictable. Or if they are predictable now, they won't be as the structure of the app inevitably changes. I don't care if the queries are active or not, and in general I can't predict whether they will be, because app code is complicated and the same mutation can be accessed from multiple places. Also ideally I'd only refetch this data if it's actually asked for again, rather than refetching it eagerly which can only lead to overfetching. In that case what apollo-client expects of me is to write manual cache manipulation, which is complex and error-prone code, and again can change unpredictably as the structure of the app and therefore the cache changes. This is completely workable and yet pretty frustrating and expensive to actually work with in practice. Ideally what apollo-client would have instead is some nice shorthand for "invalidate this piece of data when this mutation returns" and then I could just pass that and move on, rather than spending half an hour reverse-engineering the structure of the cache and writing specific code to invalidate the pieces that matter. Does that make any sense? |
It makes more clear what I have felt for quite a while: apollo is way too complex for simple cases. I have never fully understood it and it seems I have a lot to learn. Which is why I have moved on to tanstack query. Where cache invalidation is so simple, even I have grasped it. |
@daveslutzkin appreciate the response! Here's my 2 cents
I can absolutely agree here. I tend to like APIs that fit a reasonable mental model without needing to know nitty gritty or surprising details. This definitely feels like it fits into that bucket since you need to know the concept of an "active" query to use this feature with a string array. That being said, there are some performance-related concerns that we are also trying to balance here and this is something I think we do a poor job of communicating if I'm being honest. When queries stop being used, we tend to throw them away and allow the garbage collector to do its job so that we can avoid memory leaks with lots of objects building up over time. Its difficult to know when a query might or might not be used again. Since queries can "disappear" when they aren't being used, it makes sense that a query that has been thrown away can no longer be found by its name, hence why you're seeing the warning about a missing query. This doesn't mean this problem can't be solved, that the API today is perfect, or that we can't iterate on this to make it better. I'm simply trying to convey some tradeoffs we have to make that sometimes result in less-than-ideal outcomes, even if some of the benefits aren't easily seen.
This is spot on. I absolutely hear you as I've experienced this plenty myself. As an app grows in complexity, its impossible for any one developer to keep everything in their head, nor is it reasonable to expect this to be the case. The tools you use should help you, not hinder you. This is a general theme that I'd frankly like to see us tackle in v4: simplification. Apollo Client has been around for quite a while by this point, and like any project that exists for any amount of time, parts of it can grow crusty or feel complex for no reason (after all, we've been trying to make backwards compatible changes for years at this point!). These types of ergonomics are absolutely something I'd love to see us approach with v4 to make Apollo feel simple. About the best I can promise you right now is that we are absolutely looking at this and will be investing a considerable amount of time for v4 to try and remove a lot of these types of friction points. We will be sharing more in the coming months as the picture for v4 becomes clearer. @barbalex you're absolutely welcome to try out different clients and pick what suits you the most. The worst thing we can do is hold you hostage just because you're familiar with this library. Each library has its own set of tradeoffs with varying ideas on how to approach things. There are absolutely things Apollo can do that TanStack Query can't and vice-versa. Up to you to decide which set of tradeoffs work the best for you. If you'd like to help us shape the future for v4, we'd absolutely love feedback on the friction points you've experienced and what specifically makes Apollo Client feel complex to you. Apollo Client shouldn't feel complex for simple cases and I'm bummed that this is the sentiment. It just means we have an opportunity to make some improvements to remove these barriers. That being said, since this issue isn't about feedback and about Ok back to the regular scheduled programming on the topic of |
I think that's perfectly understandable. But my point here is that I don't actually want to request refetch of a query by name, I just do that because it's the way the library seems to suggest (by providing the |
@daveslutzkin ah gotcha, apologies that I misunderstood what you were getting at. Perhaps this is also something not well communicated in our docs? You can do this very thing with the const book = { __typename: 'Book', id: 5, ...otherFields }
cache.evict({ id: cache.identify(book) }) And if you want to remove dangling references to the evicted record, you can call Is this what you're looking for? |
@jerelmiller Hm, maybe? Though that should presumably be taken care of transparently by returning an object with id in the mutation response, so maybe I'm confusing myself and describing it wrong - maybe it is a query (usually a list query) not a piece of data. Just looking through our code, most of the So maybe my point is more that we don't care and don't want to care whether those queries are "active". That feels like the library's concern not ours, purely an optimisation detail. OK, so maybe what we want is to be able to say "invalidate this query so next time its result is requested, it doesn't come from the cache because we now know that cached value will be invalid". So then:
Which I think is what happens when you call But because: a) there's no then it doesn't feel like it's a recommended way to proceed. |
@daveslutzkin thanks for this clarification. I think you and I are probably using the same terms to mean different things, so I'm probably confusing you even more 😬. Apologies for that! Something to clarify is that Apollo's Rather than thinking of this as "invalidating a query", think of it more as "invalidating a field or entity" in the cache, where an "entity" is defined as a chunk of data typically keyed by its
You probably already know this information, but I wanted to state this to ensure we are talking about the same thing. If you're curious about a more in-depth look at whole query caching vs normalized caching and their behaviors, let me know and I'd be happy to add an example to explain this.
This is super helpful to know! In this case, the
I totally hear you here and and agree the current implementation is a bit of a limiting detail and a leaky abstraction. We'll see if we can come up with some strategies for making this operate a bit more reasonably while allowing for the optimizations to take place, but this is likely not something we will look at until after we release v3.8 (sometime in the next few weeks). Again, I'd still like to at least determine if this is a bug even with "active" queries so that we can classify this issue accordingly. A fix for active queries not refetching would likely be a quicker fix than determining a new strategy to make this work for all previously called queries. If you have some more details to share here to help classify this behavior, that would be helpful.
If Solutions
refechQueries: [{ query: QUERY, variables: {...} }] Take this approach with a grain of salt and a bit of caution if you decide to try this. Our codebase literally calls this approach "legacy" and we don't document it. I don't have the history or context to fully understand why this is the case, so it may come with its own quirks.
You can use mutate({
update(cache) {
// NOTE: You may have to provide an `id` option here if the field you're looking to
// invalidate is not a top-level query field.
cache.modify({
fields: {
listField(_, { INVALIDATE }) {
return INVALIDATE;
}
}
})
}
}); Check out the list of examples on how Does this help a bit more? |
It is my understanding that |
@dylanwulf oh you might be right. All this talk of invalidating data got my brain scrambled 😂.
mutate({
update(cache) {
// NOTE: You may have to provide an `id` option here if the field you're looking to
// delete is not a top-level query field.
cache.modify({
fields: {
listField(_, { DELETE }) {
return DELETE;
}
}
})
}
}); |
@jerelmiller Ah that makes more sense, thanks! I've tried that in the past and it does work for refetching, but my main problem with it is that it causes my query data to disappear from the screen until the refetch completes. Not the best user experience, so I'm still sticking to |
@dylanwulf there are definitely tradeoffs to each approach. If you know your query is "active" (like it sounds you have), then |
What I ended up doing is just placing all
|
@alessbell you were not able to reproduce the issue because your app is rendered under React When unmounting a component, only one of each duplicated queries is removed from said array, refetch is thus successful because it matches the query name with the leaked query in the array. I've removed This difference of behaviour between dev and prod build is also very confusing (took me an afternoon of debugging to understand what was going on) so we could at least work on removing the leak under strict mode ? Or maybe what's in the works for 3.8 will fix that ? |
Hi for everyone, today I got stuck with the same issue. I have component A that has a list and a form for creating items for this list. There is also component B that only has a list from component A. In dev mode, everything works correctly, but in prod mode, the list in component B does not update automatically when creating a new item, only after page reload.
|
Hi @jerelmiller! I've hit this You've said:
And yet, I seem to see the same behavior when I'm using the document (or at least I think I am). This is my code: export const GET_COLLECTIONS = gql(`
query GetCollections($input: GetCollectionsInput!){
getCollections(input: $input) {
id
name
}
}
`);
const [captureSnapshotsMutation] = useMutation(CAPTURE_SNAPSHOTS, {
refetchQueries: [GET_COLLECTIONS],
// The GET_COLLECTIONS query is not always active when this mutation runs,
// so we need to also manually evict its results from the cache. We really
// want this query to be re-executed the next time the snapshots page is
// rendered.
update(cache) {
cache.evict({id: "ROOT_QUERY", fieldName: "getCollections"});
},
}); This results in Is all this surprising / indicative of a bug? |
Hi @andreimatei, That said, it's unrelated to the problem you are having here - there are in fact three different things you can pass into the
Nr. 1. and 2. should behave pretty much the same - I believe you wanted to use 3. instead here, so your code would need to change like this: const [captureSnapshotsMutation] = useMutation(CAPTURE_SNAPSHOTS, {
- refetchQueries: [GET_COLLECTIONS],
+ refetchQueries: [{ query: GET_COLLECTIONS }], Keep in mind that this "legacy" style will always call a query with the variables you put in here, independently if the query is currently in cache or not. So it's less of a "refetch this" and more of a "fetch this". |
Got it, thank you for the explanation! |
@jpvajda No news right? :) |
Intended outcome:
After a create mutation, I want to refetch the list query to have the newly added item be displayed in the list, making use of the variables which the list query is run with previously.
As per the documentation, this should be doable:
Actual outcome:
When using the operation name as string in the refetchQueries array, no query is refetched, nothing is updated and no network activity is visible.
Versions
The text was updated successfully, but these errors were encountered: