Version: v11.0.0
Refetching Connections (Using and Changing Filters)
Often times when querying for a list of data, you can provide different values in the query which serve as filters that change the result set, or sort it differently.
Some examples of this are:
- Building a search typeahead, where the list of results is a list filtered by the search term entered by the user.
- Changing the ordering mode of the list comments currently displayed for a post, which could produce a completely different set of comments from the server.
- Changing the way News Feed is ranked and sorted.
Specifically, in GraphQL, connection fields can accept arguments to sort or filter the set of queried results:
In Relay, we can pass those arguments as usual using GraphQL variables
When paginating, the original values for those filters will be preserved:
- Note that calling
loadNext
will use the originalorder_by
andsearch_term
values used for the initial query. During pagination, these value won't (and shouldn't) change.
If we want to refetch the connection with different variables, we can use the refetch
function provided by usePaginationFragment
, similarly to how we do so when Refetching Fragments with Different Data:
Let's distill what's going on here:
- Calling
refetch
and passing a new set of variables will fetch the fragment again with the newly provided variables. The variables you need to provide are a subset of the variables that the generated query expects; the generated query will require anid
, if the type of the fragment has anid
field, and any other variables that are transitively referenced in your fragment.- In our case, we need to pass the count we want to fetch as the
first
variable, and we can pass different values for our filters, likeorderBy
orsearchTerm
.
- In our case, we need to pass the count we want to fetch as the
- This will re-render your component and may cause it to suspend (as explained in Loading States with Suspense) if it needs to send and wait for a network request. If
refetch
causes the component to suspend, you'll need to make sure that there's aSuspense
boundary wrapping this component from above. - Conceptually, when we call refetch, we're fetching the connection from scratch. It other words, we're fetching it again from the beginning and "resetting" our pagination state. For example, if we fetch the connection with a different
search_term
, our pagination information for the previoussearch_term
no longer makes sense, since we're essentially paginating over a new list of items.
Is this page useful?