Refetch Apollo queries anywhere by name and partial variables (ideal for refetching paginated queries)
npm install refetch-queriesrefetchQueries functionality. While this functionality is great and generally sufficient, it has shown some limitations when it comes to two cases :
typescript
export type QueryTarget = string | {
query: string | DocumentNode;
variables?: Record
};
export default function refetchQueries(
client: ApolloClient,
targets: QueryTarget[]
): Promise[]>
`
(refetchQueries returns a promise that resolves to the array of all the refetched query results.)
Example
Let's say you have the following query being made :
`javascript
const TodosQuery = gql
;
useQuery(TodosQuery);
`
Now, you want to refetch the query after a mutation, but without keeping track of secondary variables like limit and page. The following does not work because of missing variables :
`javascript
const addTodo = useMutation(AddTodoMutation, {
refetchQueries: [
{
query: TodosQuery,
variables: { list: "1" }
}
]
});
`
The following works but is not ideal if you have several rendered Todos queries with a different list argument and don't want to refetch them all :
`javascript
const addTodo = useMutation(AddTodoMutation, {
refetchQueries: ["Todos"]
});
`
Solution
Import the refetch function and call it after the mutation is done :
`javascript
import refetchQueries from 'refetch-queries'
const client = useApolloClient();
const addTodo = useMutation(AddTodoMutation, {
onCompleted() {
refetchQueries(client, [
{
query: TodosQuery,
variables: { list: "1" }
}
])
}
});
`
You can of course refetch by name :
`javascript
refetchQueries(client, ["Todos"])
`
And even :
`javascript
refetchQueries(client, [
{
query: "Todos",
variables: { list: "1" }
}
])
``