I am using graphql in the backend and Apollo to make calls. In ngOnInit I subscribe to a an Apollo query observable to retrieve all projects, it works fine, I add a project, then go to another component and get back so that ngOnInit is called again and I get the new project list from the server (after adding a project), but it brings the same list (before adding). If I refresh the page instead I get the new list with the new project added. I tried unsubscribing in onDestroy but still no luck. I tried to use watchQuery but apparently my Apollo version doesn't have valueChanges using Apollo anguoar 0.11.0, the only one that worked with my angular 4 project.
1
votes
Maybe there is a problem with the cache. Try to add a parameter in your graphql request depending on the current time. Something like &time=Date.now().toString(). Even if your graphql doesn't use this parameter. It permits to force Apollo to make a new request and get the true results.
- Powkachu
Thanks for the comment, yes it was a problem with the cache, i did client.resetStore() to my apollo client in ngOnDestroy() and it did the trick. If this was an answer i would have marked it as solution, your approach to solve the problem is definitely better than mine.
- Ala Abid
I can make an answer and you can mark it as solution. ^^
- Powkachu
sure, go ahead!
- Ala Abid
That's an interesting approach for overcoming the issue. But I'm curious if this version of Apollo angular doesn't support fetchPolicy?
- Venkat
1 Answers
3
votes
The problem comes from Apollo's cache. As you're making the same request, it reuses the previous result it got from the request.
There are multiple solutions to force it to not use cache.
As I suggested in comments, you can put a HTTP parameter which will change for every HTTP request. For example, something depending on current time like &time=Date.now().toString(). Every request will be different so Apollo won't use cache.
But you can also (as you said), and it's maybe better, just reset it by putting client.resetStore() in ngOnDestroy(). It will cause the store to be cleared and all active queries to be refetched. (source)