How to use signals as query keys and react to changes?
Hi everyone, I'm trying to get a reactive query using signals. This is my setup:
For example, I have a signal that represents the id of the selected todo. I want to use this signal as the query key for my query.
The problem is that when the signal key changes, the query remains the same. It doesn't react to the signal change.
This code is taken from the docs (https://tanstack.com/query/v5/docs/framework/angular/guides/query-keys), but it doesn't work:
The query fetches the first time is created, but when
todoId
changes, it stays the same.
I tried converting the query to a computed signal, to react to the changes.
But this creates an error due to it being a function called in the template (I think).
Any ideas on how to react to signal changes?Overview | TanStack Query Docs
TanStack Query (FKA React Query) is often described as the missing data-fetching library for web applications, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your web applications a breeze.
Motivation
4 Replies
like-gold•2y ago
Hi, this should work but I heard this before and it might be that change detection is not triggered. What kind of Angular application is this? Standard CLI?
other-emeraldOP•2y ago
Hey, thank you for taking the time to respond. I've been playing a little more with this and I figured my mistake.
What I was doing was to store the query in a service and then using it in my component expecting it to be reactive. Say:
Of course, using it as a function causes it to run only once, when the component is created.
My thinking behind this was that I wanted to reuse this query in other components, That's why I put it in a service.
The solution was to use
injectQuery
directly in the component, and then use the QueryClient
to get the data in other parts of the app.like-gold•2y ago
The solution was to use injectQuery directly in the component, and then use the QueryClient to get the data in other parts of the app.If that is in services I think that's fine but if it's in other components you might want to consider using a query there as well with the same query key. It will be de-duplicated so requests will not be fired unnecessarily. I am still developing the Angular adapter itself but I hope to have some time soon to describe architectural patterns. Thanks for the update and good to know that it's not a bug in Angular Query 😅
conscious-sapphire•17mo ago
The difference here is that the call to get the signal value must be inside the injectQuery callback. It's the same way that
computed
works in Angular: