TanStackT
TanStack2y ago
4 replies
verbal-lime

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:

todoId = signal(-1)

injectQuery(() => ({
  enabled: todoId() > 0,
  queryKey: ['todos', todoId()],
  queryFn: () => fetchTodoById(todoId()),
}));

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.

todo = computed(() => injectQuery(() => ({
  enabled: todoId() > 0,
  queryKey: ['todos', todoId()],
  queryFn: () => fetchTodoById(todoId()),
})));


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?
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
Was this page helpful?