I am having an issue with refetching queries in apollo-client after mutation. Hope someone can help.
My graphql schema has one query and one mutation:
type Query {
alerts(filter: AlertFilter!): AlertsResponse!
}
type Mutation {
closeAlert(input: CloseAlertRequest!): CloseAlertResponse!
}
The alerts
query accepts an AlertFilter with status = OPEN or CLOSED. It returns a list of alerts along with open & closed alert counts.
The closeAlert
mutation closes the specified alert.
What I am trying to do is to refetch the alerts
query whenever the closeAlert
mutation is called. This is to make sure that I have the latest list of alerts + the latest open/close counts.
Here's how I have coded my closeAlert
mutation. It is trying to refetch the alertsPage
query after the mutation.
export function useCloseAlert() {
return useMutation(closeAlertDocument, {
refetchQueries: ['alertsPage'],
});
}
My alertsPage
query is coded like this:
const alertsPageDocument = graphql(/* GraphQL */ `
query alertsPage($filter: AlertFilter!) {
alerts(filter: $filter) {
alerts {
id
...AlertItem
}
counts {
status
count
...AlertCountItem
}
}
}
`);
However, looking at the Apollo Client DevTools extension, I see that there are two distinct alertsPage
queries in the cache (see screenshot below): one for filter status="OPEN"
and another for filter status="Closed"
. The mutation only refetches the query for filter status="OPEN"
- I can see the open count go down and closed count go up. However the query for filter status="CLOSED"
is not refetched and the counts don't change at all.
Question: How can I tell Apollo client to refetch all alertsPage
queries, regardless of the input values?
Answering my own question...
In order to refetch both queries (for status=OPEN and status=CLOSED), I had to change refetchQueries
as follows:
export function useCloseAlert() {
return useMutation(closeAlertDocument, {
refetchQueries: [
{
query: AlertsPageDocument,
variables: {
filter: { status: 'OPEN' },
},
},
{
query: AlertsPageDocument,
variables: {
filter: { status: 'CLOSED' },
},
},
],
});
}