refetch-queries
TypeScript icon, indicating that this package has built-in type declarations

3.0.0 • Public • Published

refetch-queries

Refetch Apollo queries anywhere by name and partial variables (ideal for refetching paginated queries).

Description

This module serves as an extension for Apollo's mutation refetchQueries functionality. While this functionality is great and generally sufficient, it has shown some limitations when it comes to two cases :

  • Refetching paginated / filtered queries.
  • Refetching queries anywhere (not just after a mutation)

The first problem is solved by being able to target observable queries by partial variable match rather than deep equality. The second is solved by the fact you'll basically be given a function that you can call from anywhere.

Exports and signatures

export type QueryTarget = string | {
  query: string | DocumentNode;
  variables?: Record<string, any>
};
 
export default function refetchQueries(
  client: ApolloClient<any>,
  targets: QueryTarget[]
): Promise<ApolloQueryResult<any>[]>

(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 :

const TodosQuery = gql`
  query Todos($list: ID!, $limit: Int!, $page: Int!) {
    todos(list: $list, limit: $limit, page: $page)
      @connection(key: "todos", filter: ["list"]) {
      id
      label
    }
  }
`;
 
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 :

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 :

const addTodo = useMutation(AddTodoMutation, {
  refetchQueries: ["Todos"]
});

Solution

Import the refetch function and call it after the mutation is done :

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 :

refetchQueries(client, ["Todos"])

And even :

refetchQueries(client, [
  {
    query: "Todos",
    variables: { list: "1" }
  }
])

Package Sidebar

Install

npm i refetch-queries

Weekly Downloads

20

Version

3.0.0

License

MIT

Unpacked Size

8.24 kB

Total Files

7

Last publish

Collaborators

  • strblr