简体   繁体   中英

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.

'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 fe

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 )}

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