Search code examples
javascriptreact-nativegraphqlapolloapollo-client

useLazyQuery - Re-Rendering Issue


Requirement:

I want to call the query the 1st time automatically in useEffect and then manually in the functions.

Issue: Invarient Violation: Too many re-renders.

 const [getComment, { loading, data }] = useLazyQuery(getCommentsQuery);
  useEffect(() => {
    getComment({
      variables: {
        input: {
          id: "5e5cb512e90bd40017385305",
        },
      },
    });
  }, []);

  if (data && data.getPost) {
    var allNewComments = data.getPost.comments;
    setAllComments(allNewComments);  // re-renders
  }

setState is causing this issue, I'm assuming.


Solution

  • 'Body parts' of functional component are run for every change, needs conditions (or useEffect hooks) to block unexpected behaviours.

    Just don't use useState for allComments? You can use f.e.

    const allNewComments = (data && data.getPost) ? data.getPost.comments : [];
    

    ... if you want to iterate over allNewComments

    If you still want to use useState (in combination with useLazyQuery) ... use it in onCompleted option/handler, sth like:

    const [getComment, { loading, data }] = useLazyQuery(getCommentsQuery, {
      variables: {
        input: {
          id: "5e5cb512e90bd40017385305",
        },
      },
      onCompleted: (data) => {setAllNewComments( data.getPost.comments )}