Refetch Query with Different Parameters in Apollo GraphQL Client (Angular)

66 Views Asked by At

I have a GraphQL query that I am filtering on, so I refetch it after user input. I am simply wondering if it is possible to refetch this query successfully if I add or remove variables to the query. I don't see anything in the documentation defining the requirement of matching parameters.

Currently, if I add a parameter to the query during the refetch call, it executes the query but does not broadcast that result to the same observable, so my subscribe method does not get re-called.

Is this behavior documented somewhere? Is there a way to retain the observable reference while adding or removing parameters?

data.service.ts

getData(search?: string, sort?: Sort[]) {
  return this.apollo.watchQuery<{query: Data[]}>({
    query: myQuery,
    variables: {
      search: search,  // search parameter will not be defined in query when not passed
      orderBy: sort,
    },
  });
}

search.component.ts

query: QueryRef;

ngOnInit() {
  this.query = this.dataService.getData();
  this.query.valueChanges.subscribe({
    next: value => {
      // this is called on component init
      // but not called after handleSearchChange calls refetch
      // if I change the query to initialize the search parameter with an empty "" string
      // the refetch will result in this subscription being called
      // ostensibly because the QueryRef requires matching parameters to match the Observable
      // but there are situations I can imagine where adding or removing parameters to the query
      // might be helpful without losing the observable reference
      // is there documentation about this behavior or syntax that allows adding parameters?
    },
  });
}

handleSearchChange(searchText: string) {
  this.query.refetch({
    search: searchText,
  });
}
0

There are 0 best solutions below