如何用useQuery和subscribeToMore取消订阅[英] how to unsubscribe with useQuery and subscribeToMore

本文是小编为大家收集整理的关于如何用useQuery和subscribeToMore取消订阅的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

另一个帖子分享了如何取消订阅的示例,其中<一个href ="https://www.apollograph ql.com/docs/reacect/api/reacect-hooks/#usequery"rel ="noreferrer"> apollo docs not. apollo文档提及了什么子命令返回...

subscribeToMore:设置订阅的函数. subscribeToMore返回可以用于取消订阅的函数.

这确实给了一个提示.它有助于看到一个例子.

问题

使用@apollo/react-hooks,在useEffect()的内部并返回subscribeToMore的结果,这是在组件上取消订阅的方式?

const { data, error, loading, subscribeToMore } = useQuery(GET_DATA)

useEffect(() => {
    const unsubscribe = subscribeToMore(/*...*/)
    return () => unsubscribe();
}, [])

推荐答案

在组件卸载时,任何相关的订阅都应为您取消订阅.除非您希望在那之前取消订阅,否则不得不手动管理它.

当subscribeToMore称为https://github.com/apollographql/apollo -client/blob/155536f26C335A2242F26C335A2242F24E2/SRC/CORE/OBServableSquery.ts#l385"rel =在这里然后在清除查询这里.

其他推荐答案

subscribetomore返回取消订阅函数,因此您的代码是正确的.

https://github.com/apollographql/apollo-client/issues/5245

本文地址:https://www.itbaoku.cn/post/1938056.html

问题描述

Another post shared an example of how to unsubscribe, where the Apollo docs don't. The Apollo docs do mention what subscribeToMore returns...

subscribeToMore: A function that sets up a subscription. subscribeToMore returns a function that you can use to unsubscribe.

This does give a hint. It would help to see an example.

the question

Using @apollo/react-hooks, inside of a useEffect() and returning the results of the subscribeToMore, is this the way to unsubscribe on a component unmount?

const { data, error, loading, subscribeToMore } = useQuery(GET_DATA)

useEffect(() => {
    const unsubscribe = subscribeToMore(/*...*/)
    return () => unsubscribe();
}, [])

推荐答案

Any associated subscriptions should be unsubscribed for you when the component unmounts. You shouldn't have to manually manage it unless you want to unsubscribe before then.

You can see the subscription being tracked when subscribeToMore is called here and then unsubscribed when the query is being cleaned up here.

其他推荐答案

SubscribeToMore returns the unsubscribe function, so your code is correct.

https://github.com/apollographql/apollo-client/issues/5245