facebook / facebook/relay

useRefetchableFragment makes an unnecessary node query on nested fields

Open
#4,240 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
Rust
Stars
19k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

I'm using `usePaginationFragment`/`useRefetchableFragment` to load data for a searchable typeahead, with `refetch` being called in a `useEffect(..)` which triggers each time the (debounced) input value has changed.

```ts
const [{ ships }, refetch] = useRefetchableFragment(graphql`
fragment ShipsList_faction on Faction
@argumentDefinitions (
search: { type: "String", defaultValue: "" }
)
@refetchable(queryName: "ShipsListPaginationQuery")
{
ships(search: $search) {
edges {
node {
name
}
}
}
}
`, faction);

useEffect(() => {
refetch({ search: searchTerm })
}, [searchTerm]);
```

This fragment is on the `Faction` type (which implements `Node`) is fetched from the following query:

```ts
const result = useLazyLoadQuery(graphql`
query AppQuery {
faction {
...ShipsList_faction
}
}
`, {});
```

The issue is the refetch call after the initial render doesn't seem to make a cache hit & instead makes another network call for the `ShipsListPaginationQuery` refetch query even though the inputs should be the same.

Screenshot 2023-03-08 at 22 38 16

This example is available [on a branch here](https://github.com/beaumontjonathan/simple-relay-graphql-playground/tree/refetch-pagination-on-input).

If I instead resolve `ships` from the root `Query` rather than on a `Faction`, then the node query doesn't happen.

This is particularly annoying in one application where I'm using `useEffect(() => refetch({ search }), [search])` for multiple UI items, so on the initial page load it sends of several unnecessary network requests.

- Is there a particular reason this query needs to be refetched, or could this be considered a bug?
- Would there be a better way to load data without needing the `useEffect(..)`?

Thanks for any help :)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.