Skip to content

Patterns for keeping "list of items" and "individual item" in sync? #2679

Answered by TkDodo
bywo asked this question in Q&A
Discussion options

You must be logged in to vote

updating the item within the list when the item is fetched (and vice versa)

I think you an achieve that by writing to the cache in onSuccess, something like:

useQuery(
  ['todos', id],
  () => fetchTodo(id),
  {
    onSuccess: (newTodo) => {
        queryClient.setQueryData(['todos'], (old) => old?.map(todo => todo.id === id ? newTodo : todo) ?? [])
    }
  }

it would also work the other way around: onSuccess of the list query, you create a bunch of detail query entries.

It'd be nice if an update to one automatically propagated to the other.

for that to work, an underlying schema would be needed that react-query doesn't have. queries and mutations don't know what they are actually do…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@bywo
Comment options

@dburles
Comment options

@TkDodo
Comment options

Answer selected by bywo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants