Reputation: 5135
I'm very new to React and GraphQL(Apollo) and learning the stack.
I have a React Component that loads some page data and there is a "Reload" button on the page.
Problem:
- I want to refetch the data when I click on "Reload" button.
- However, I could not find a way to refetch the data from queryObservable.
- How do I refetch the data from QueryObservable? Is there anyway to call refetch?
I tried using reFetchObservableQueries()
however, this reloads the page and refetches everything. Can I specifically refetch only a single observable?
This is my code:
getPageQueryObservable = (contentId, key, paginated = false) => {
const query = contentId ? TreeQuery : RootLevelQuery;
const defaultVariables = 'Test';
const variablesForPagination = {
paginationLimit: INITIAL_PAGE_SIZE,
...defaultVariables
};
return this.props.apolloClient.watchQuery({
query,
variables: paginated === true ? variablesForPagination : defaultVariables
});
};
loadPages = async (paginated = false) => {
const { pages: localPages } = this.state;
const { id, key } = this.props;
const queryObservable = this.getPageQueryObservable(
id,
key,
paginated
);
// I want to ideally call this stuff again..When "Reload" button is clicked.
this.querySubscription = queryObservable.subscribe({
next: ({ data, loading }) => {
....
});
Upvotes: 0
Views: 1277
Reputation: 84657
You can call query
with the same query and variables but a fetchPolicy
of network-only
in order to refetch the query. This should update the cache and therefore any relevant Observables.
await client.query({ query, variables, fetchPolicy: 'network-only' })
However, there's really no reason to use watchQuery
directly. Instead, you should use the hook API to fetch and refetch your data.
const { data, loading, refetch } = useQuery(query, { variables })
Not only does this reduce boilerplate, but now refetching is as simple as
await refetch()
Upvotes: 1