apollo-client: Fetch more function is undefined for useLazyQuery react-apollo hook

I use react-apollo useLazyQuery hook. My goal to use it in fetch more button click. However, when I try to use it the fetchMore function is undefined.

Here the call to it:

const [getMyData,{ loading, data, fetchMore }] = useLazyQuery(
    myQuery,
    {
      notifyOnNetworkStatusChange: true,
      fetchPolicy: 'network-only',
      variables: {}
})

Even if I run lazy on component ready, fetchMoreStill undefined. The question is why it is undefined?

“apollo-client”: “^2.6.4”, “react-apollo”: “^3.1.3”,

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 6
  • Comments: 21 (2 by maintainers)

Most upvoted comments

I was able to solve mine by checking if fetchMore is undefined like: if (fetchMore === undefined) return; fetchMore({});

I ran into this today and the fetchMore that is undefined seems to be internal to the hook.

TypeError: Cannot read property 'fetchMore' of undefined
    at QueryData._this.obsFetchMore (QueryData.ts:493)

It appears to be undefined before the query is fired (this makes sense to me) and when loading is true.

Checking loading, called, and the returned data before calling fetchMore seemed to fix my issue

In 3.5.0 (which is in RC and which you can download @apollo/client@beta), the methods will always be defined!

This should now be resolved in @apollo/client@3.5.0. Let us know if you notice any issues. Thanks!

Upgraded to 3.4.16 and can confirm that checking that fetchMore isn’t undefined before calling seems to do the trick.

Would be great if the docs actually clarified that fetchMore can be undefined (https://www.apollographql.com/docs/react/api/react/hooks/#fetchmore. Note this links to the docs on useQuery, even though I tapped the fetchMore under useLazyQuery). And if there was some notes on the relationship between called and fetchMore.

IE, I was writing (called && fetchMore ? fetchMore : runQuery)({ variables: ... }), but the more simple (fetchMore ?? runQuery)({ variables: ... }) seems to have the exact same effect.

Lovely, @sashberd . My workaround was to refactor all useLazyQuery-related code into a custom React hook. For some reason, doing all the fetchMore work and new calls in a separate hook works whereas doing it within the same component doesn’t. May be an interesting avenue to explore.