如何操作:取消订阅Apollo(subscribeToMore)订阅?

时间:2019-07-27 19:17:46

标签: reactjs apollo react-apollo apollo-client

因此,我有一个订阅,希望取消订阅:

              <DeleteItem 
                id={item.id}
                urlReferer={urlReferer}
                subscribeToDeleteItems={() =>
                  subscribeToMore({
                    ....
                    }
                  })
                }
              >Delete This Item</DeleteItem>

DeleteItem.js

const DeleteItem = props => {
  const {urlReferer} = props;

  useEffect(() => {
    props.subscribeToDeleteItems();
  },[urlReferer]);
  ...
  }
...
}

我该怎么做?

2 个答案:

答案 0 :(得分:0)

所以我通过调用abortController实现了清理:

  useEffect(() => {
    const abortController = new AbortController();
    props.subscribeToDeleteItems();
    return () => {
      abortController.abort();
    };
  },[urlReferer]);

答案 1 :(得分:0)

如果您的效果返回了一个函数,React将在需要清理时运行它。 SubscribeToMore返回取消订阅功能。

const subscribeToNewComments = () =>
    subscribeToMore({
      document: MESSAGES_SUBSCRIPTION,
      variables: { channelId },
      updateQuery: (prev, { subscriptionData }) => {
        if (!subscriptionData) return prev;
        return Object.assign({}, prev, {
          channelMessages: [
            subscriptionData.data.messageAdded,
            ...prev.channelMessages,
          ],
        });
      },
    });   

React.useEffect(() => {
        let unsub = subscribeToNewComments();
        return () => {
          unsub();
        };
      }, [channelId]);