T
TanStack2y ago
sunny-green

Invalidating query during mutation not working

So, I have a problem I'd like to ask about that is quite elementary. I've built a simple ToDo app on a single page. The problem is I can't get the "invalidateQueries" to work after mutating the data in my database.
Initial list of items:
const getTodos = () => fetch('http://localhost:3000/api/todos').then(response => response.json()) const { isLoading, isError, data, error } = useQuery({ queryKey: ['todos'], queryFn: getTodos, })
Mutating the list:
const { mutate } = useMutation({ mutationFn: newTodo => useFetch(http://localhost:3000/api/addtodos, { method: 'post', body: { newTodo }, }), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['todos'] }) //This isn't working }, })
As I said, the invalidation doesn't seem to have any effect. The list doesn't update until I click outside the window or wait. However, if I add a plain function triggered by a button I can get the invalidation to work right away:
<button @click="runInvalidate">Invalidate</button> function runInvalidate() { queryClient.invalidateQueries({ queryKey: ['todos'] }) }
I posted this the sponsor channel with more of the code and @TkDodo 🔮 thought it looked like I'd set things up right.
Thanks for your help!
16 Replies
ratty-blush
ratty-blush2y ago
@MrMentor maybe you can have a look?
sunny-green
sunny-greenOP2y ago
FYI: I found this old thread https://discord.com/channels/719702312431386674/1029469840165064724/1029529421985632366 that suggested clearing the cache and reinstalling. I ran npx nuxi cleanup and deleted the node_modules folder and ran npm install However no change to the problem.
quickest-silver
quickest-silver2y ago
That problem was more about packages not being properly updated. Question to you is where are you getting your queryClient from? I do not see it in the example code. Minimal reproduction could also be helpful.
sunny-green
sunny-greenOP2y ago
Hi - thanks for helping! Fair warning - I'm an old dog trying to learn new tricks so please be patient. I last did real web development in the 90's with ColdFusion!
I think the QueryClient is created in the vue-query.ts file in my plugins folder. I just have the suggested code from your docs at the top of this page: https://tanstack.com/query/v5/docs/vue/guides/ssr
SSR | TanStack Query Docs
Vue Query supports prefetching multiple queries on the server and then dehydrating those queries to the queryClient. This means the server can prerender markup that is immediately available on page load and as soon as JS is available, Vue Query can upgrade or hydrate those queries with the full functionality of the library. This includes refetc...
sunny-green
sunny-greenOP2y ago
I also have the following code at the top of my script section:
import { useQuery, useMutation, useQueryClient } from '@tanstack/vue-query' const queryClient = useQueryClient()
Maybe that's what you meant.
quickest-silver
quickest-silver2y ago
It looks ok. Not sure what to tell you though, cause it seems to be working fine. https://codesandbox.io/p/sandbox/objective-hermann-jcx52t?embed=1&file=%2Fsrc%2FPosts.vue%3A9%2C20 It must be an issue with you code. So unless you will be able to trim down your code to something you could share with us, there is not much we could help you with. It might also be the case that library is working fine, but something else is not. You might want to check if network call is made in the browser devtools. Maybe your backend returns with cache headers set, so browser is caching calls instead of calling the backend.
sunny-green
sunny-greenOP2y ago
My entire code is only 61 lines long. I've taken two screen shots, one of the template section and one of the script section. Please let me know if that's an OK way to share or how else I should do this.
I will look into the other issues you mentioned. Thanks for taking a look!
No description
No description
quickest-silver
quickest-silver2y ago
Well, it looks good. 🤷‍♂️ Also you can install vue-devtools to peak into the query cache. No need for console logging.
sunny-green
sunny-greenOP2y ago
Looking at the Network part of the dev tools I see two requests when I click the "Add Todo" button: #1 Name: addtodos Status: 200 Type: fetch Initiator: ofetch.00501375.mjs?v=bc775003 #2 Name: todos Status: 304 Type: fetch Initiator: tanstacktest.vue OK - will try that next... I have this installed: Nuxt DevTools v0.8.3. Is that OK?
quickest-silver
quickest-silver2y ago
the second one seems to be the query for todos, but gets 304 not modified. So your backend seems to not know about new todo.
quickest-silver
quickest-silver2y ago
Vue.js devtools
Browser DevTools extension for debugging Vue.js applications.
sunny-green
sunny-greenOP2y ago
Aha! I did have that installed but I hadn't really used it yet. What would you like me to check with this? I see the ["todo"s"] query go from fresh to stale after 5 seconds which I think is the default. When I click my add ToDo button it returns to fresh but the item isn't added to the list (which makes sense if its not getting the latest data). There is a QueryCache2 output below - is there something there I should check?
quickest-silver
quickest-silver2y ago
If it's getting to fresh then vue-query made the request and got new data (or old in your case). So your mutation to the server: - does not seem to properly add todo - adds it after some time - or you have some additional cache on the backend side. vue-query seems to work properly
sunny-green
sunny-greenOP2y ago
I'm not sure... My mutation adds the data right away (I can see in SupaBase).
If I click my "runInvalidate" button, it works right away. So the following code does NOT work in the onSuccess method after mutating, but does work right away outside of the mutation.
queryClient.invalidateQueries({ queryKey: ['todos'] })
Hmm - Nuxt3 comes with the Nitro server. I'm looking into caching on their part. Thanks for helping me!
quickest-silver
quickest-silver2y ago
you could try to maybe wrap invalidateQueries in a setTimeout with like 1000 ms and see if it works. It might be the case that it's just too fast to re-fetch then you would need to look at your server to see why it's not instantly available. button invalidate potentially works, cause you are clicking on it after some time, not 2ms after mutation finishes Also check if request to /todos does not return any cache headers
sunny-green
sunny-greenOP2y ago
Interestingly wrapping the invalidation in a 10 second timeout still doesn't work. However, thanks to your tip I have found the cache that the nitro engine is using for api requests! It is under .nuxt/cache/nitro/handlers/_ The content of the file at the moment is: {"expires":1695850091581,"value":{"code":200,"headers":{"etag":"W/"Rl7fWPg6qt"","last-modified":"Wed, 27 Sep 2023 21:28:10 GMT","cache-control":"s-maxage=1, stale-while-revalidate"},"body":[{"id":1,"title":"test1"},{"id":2,"title":"test2"}]},"mtime":1695850090584,"integrity":"JNgfNYQBy2"} So it looks like I have to figure out how to turn off caching via the NUXT config (at least I'm guessing). Hi MrMentor, I just wanted to check back. Do you know if people are successfully using the Nuxt3 server api with TanStack Query? I'm just way down in the weeds trying to mess with the Nitro server but maybe it shouldn't be this painful? Thanks for any advice.

Did you find this page helpful?