Mehmet Ali Peker
Mehmet Ali Peker

Reputation: 721

Apollo: Refetch Queries with Delay

Can I use refetchQueries with some delay. Can I set a delay or can I call refetchQueries in a function? Thanks!

Upvotes: 4

Views: 3104

Answers (1)

hboylan
hboylan

Reputation: 397

I was unable to find an elegant way to delay refetchQueries. Instead, I just modify the cache directly as mentioned farther down this section of the documentation. https://www.apollographql.com/docs/react/caching/advanced-topics/#updating-after-a-mutation

Here's a snippet from my solution. The reason I loop through sortPermutations is that the query may have cached data for different sets of variables. This solution loops through all of them.

const [createUser] = useMutation<AddUser, AddUserVariables>(ADD_USER, {
  update: (cache, { data }) => {
    if (!data?.addUser) return

    const cachedUsers = cache.readQuery<GetUsers>({
      query: GET_USERS,
      variables: sortedColumn,
    })

    sortPermutations.forEach(({ sortBy, sortOrder }) => {
      const users = [data.addUser, ...(cachedUsers?.users ?? [])].sort(
        sortUsers(sortBy, sortOrder),
      )

      cache.writeQuery<GetUsers, GetUsersVariables>({
        data: { users },
        query: GET_USERS,
        variables: { sortBy, sortOrder },
      })
    })
  },
})

Upvotes: 1

Related Questions