简体   繁体   中英

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.

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

The question is why it is undefined?

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

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

在此处输入图片说明

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM