apollo graphql subscription firing two times

40 Views Asked by At
//post object
{
  post: {
    id: 1,
    owner: 2,
    likes: 0,
    title: "hey how r u?",
    comments: [{ id: 1, comment: "done" }, { id: 2, comment: "byee"} ]
  }
}

//this fires once but showing error that post all other columns("likes", "title", "owner", "id") except comments are missing
useEffect(() => {
    subscribeToMore({
      document: SUBSCRIBETOMORECOMMENT,
      onError: err => console.log(err),
      updateQuery: (prev: { post: postpagetype } , { subscriptionData }: commentsubscriptiondatatype) => {
        const subdata: subdatatype = subscriptionData?.data;        
        if (!subdata) return prev;        
        const newComment: commenttype[] = subdata?.newComment;       
         return Object.assign({}, prev, {
           post: {              
             comments: [...newComment, ...prev?.post.comments]
           }
         });
       }};
      }
    });
  }, []);

 // after this change it fires multiple times with no error.
useEffect(() => {
    ...
           
   return Object.assign({}, prev, { 
     post: {
       ...prev?.post, //now errors disappear but it get fires multiple times
       comments: [...newComment, ...prev?.post.comments]
     }
   }); 

  ...
},[]}

hey guys, I am working on react project with graphql and my apollo graphql subscription is firing multiple times on adding new comment in react, I am not able to find what i am doing wrong, can someone give me suggestions please, thanks in advance.

0

There are 0 best solutions below