Ad

Can I Read Each Response From Batched Mutations? [Apollo UseMutation]

- 1 answer

Let's say I have defined a mutation like this:

const [deleteItem, {data}] = useMutation(deleteItemMutation)

and then call deleteItem(id) repeatedly inside a loop, is there a way I can read each {data} response? The mutations are batched, and the response is an array (I can see that by inspecting the network traffic). However, the {data} variable only contains the response from the last batched mutation. This makes sense, of course, but I'd still be interested in the results from all of them. Any idea how I could do this?

I'm considering wrapping the mutation in another function that would take a callback, and I think that would solve the problem. But is there an easier solution?

Ad

Answer

The mutate function returned by the hook returns a Promise that will resolve with the mutation result. So while the data prop is returned by the hook as a convenience, there's no need to use necessarily use it.

const items = ['a', 'b', 'c']
const results = await Promise.all(items.map(async (itemId) => {
  const { data } = await deleteItem({ variables: { itemId } })
  return data
}))
console.log(results[0].data)
Ad
source: stackoverflow.com
Ad