2

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.

  useEffect(()=>{
    getMyData()
  },[])

The question is why it is undefined?

"apollo-client": "^2.6.4", "react-apollo": "^3.1.3",

AlexBerd
  • 1,368
  • 2
  • 18
  • 39

2 Answers2

0

You need to run the loadItem first. My case also loads on demand because I'm using SSR.

Here is my work around, check the fetchMore is undefined to make the decision

enter image description here

function NewItemListingPagination({
  initialItems,
  initialPage,
  initialLimit,
  initialTotal,
  className
}: ComponentPropTypes) {
  const { t } = useTranslation(['homepage', 'common'])
  const page = useRef<number>(initialPage)
  const [loadItem, { loading, data, fetchMore }] = useLazyQuery(FEED_NEW_ITEM)

  async function loadMore(): Promise<void> {
    const newPage = page.current + 1
    const offset = (newPage - 1) * initialLimit
    page.current = newPage

    if (!fetchMore) {
      loadItem({
        variables: {
          limit: 12,
          offset
        }
      })
    } else {
      fetchMore({
        query: FEED_NEW_ITEM,
        variables: {
          limit: 12,
          offset
        },
        updateQuery: (previousResult, {fetchMoreResult}) => {
          console.log('dddd', previousResult, fetchMoreResult)
          return previousResult
        }
      })
    }
  }

  const items = !data ? initialItems : initialItems.concat(data.feed.items)

  return <div></div>

NOTE: this code may not optimized, I just want to show the flow of fetchMore.

Phat Tran
  • 3,404
  • 1
  • 19
  • 22
-2

I am also new to react but as far as I know you have to use refetch and than give it a name like this:

const [getMyData,{ loading, data, refetch: fetchMore }] = useLazyQuery...

you can do the same thing with data and loading.

const [getMyData,{ loading: myLoading, data: myData, refetch: fetchMore }] = useLazyQuery...
Dharman
  • 30,962
  • 25
  • 85
  • 135
Luc
  • 15
  • 2
  • nope, it's just renaming ... usable when many hooks used within one component – xadm Aug 26 '20 at 07:07
  • 1
    Ah, okay. That makes sense. I thought you you had to use the keywords to rename it. Should I just delete my answer then? I am new to this. – Luc Aug 26 '20 at 07:50