apollographql / apollo-client

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
https://apollographql.com/client
MIT License
19.34k stars 2.66k forks source link

fetchMore not hitting onError and causing an infinite loop of queries #11881

Open molyholy opened 3 months ago

molyholy commented 3 months ago

Issue Description

Hello! I'm encountering a peculiar behavior when using fetchMore for pagination. I'm noticing that if the initial call to useQuery succeeds, but then a subsequent call to fetchMore fails, then onError is never called. Instead, onComplete is called and the response object will contain the result from the initial, successful useQuery call (presumably because it's cached by Apollo via the cache field policy, but i'm not sure of the specifics).

However, this leads to fetchMore being called infinitely. onComplete is where we call fetchMore, and since onComplete is being called instead of onError, and response will always exist, then fetchMore is just going to be called again and again. Is this a bug with Apollo? Or is there any way to force fetchMore to stop when it encounters an error?

Below is a simplified version of my code. I've also provided a working example via codesandbox. Essentially, the initial useQuery call is successful, but then I pass in garbage params into the fetchMore to force an error which should simulate what it's like for the fetchMore to encounter an API error in real code.

const { data, fetchMore } = useQuery(QUERY, { // this initial useQuery call works fine
    notifyOnNetworkStatusChange: true,
    variables: {
      params: {
        pagesize: 1,
      },
    },
    onCompleted: response => {
      console.log('response: ', resopnse); // this contains the data from the initial successful useQuery call
      if (response?.next) {
        fetchMore({
          variables: {
            params: {
              pagetoken: 'bogus', // bogus token to force an error
            },
          },
        });
      }
    },
    onError: err => { // this is never called even when fetchMore results in an error
      console.log('on error: ', err);
    },
  });

Link to Reproduction

https://codesandbox.io/p/devbox/wonderful-tdd-4hhnpl?file=%2Fsrc%2Findex.jsx%3A47%2C17

Reproduction Steps

Open up the codesandbox, open up dev tools and look at the console logs. There should be an infinite loop of queries

@apollo/client version

^3.7.15

alessbell commented 3 months ago

Hi @molyholy 👋

Thanks for this detailed description and reproduction. I've taken a quick look and also noticed this open issue: https://github.com/apollographql/apollo-client/issues/6857

I don't have an answer right now, but I've put this on our team's agenda for discussion and hope to get back to you soon with more info :) Thanks!

molyholy commented 3 months ago

Thank you :)!

molyholy commented 3 months ago

Hey sorry to bother you all, but is there any update on this?