FetchMore : Request executed twice every time

Viewed 2755

I am trying to implement pagination in a comment section.

I have normal visual behavior on the website. When I click the get more button, 10 new comments are added.

My problem is the request is executed twice every time. I have no idea why. The first time, it is executed with a cursor value, the second time without it. It seems that the useQuery hook is executed after each fetchMore.

Any help would be appreciated. Thanks!

component :

export default ({ event }) => {
  const { data: moreCommentsData, fetchMore } = useQuery(getMoreCommentsQuery, {
    variables: {
      id: event.id,
    },
    fetchPolicy: "cache-and-network",
  });
  const getMoreComments = () => {
    const cursor =
      moreCommentsData.event.comments[
        moreCommentsData.event.comments.length - 1
      ];
    fetchMore({
      variables: {
        id: event.id,
        cursor: cursor.id,
      },
     updateQuery: (prev, { fetchMoreResult, ...rest }) => {
        return {
          ...fetchMoreResult,
          event: {
            ...fetchMoreResult.event,
            comments: [
              ...prev.event.comments,
              ...fetchMoreResult.event.comments,
            ],
            commentCount: fetchMoreResult.event.commentCount,
         },
        };
      },
    });
  };
  return (
    <Container>
      {moreCommentsData &&
      moreCommentsData.event &&
      moreCommentsData.event.comments
        ? moreCommentsData.event.comments.map((c) => c.text + " ")
        : ""}

      <Button content="Load More" basic onClick={() => getMoreComments()} />
    </Container>
  ); 
};

query :

const getMoreCommentsQuery = gql`
  query($id: ID, $cursor: ID) {
    event(id: $id) {
      id
      comments(cursor: $cursor) {
        id
        text
        author {
          id
          displayName
          photoURL
        }
      }
    }
  }
`;
4 Answers

Adding

nextFetchPolicy: "cache-first"

to the useQuery hook prevents making a server call when the component re renders.

This solved my problem.

Could it be that the second request you are seeing is just because of refetchOnWindowFocus, because that happens a lot...

I had a similar problem and I solved it by changing the fetchPolicy to network-only.

It only makes one request if you are worried about that but the react component refreshes but not rerender each time an item in the useQuery hook changes.

Take for instance it would refresh the component when loading changes, making it seem like it sends multiple requests.

Related