Как отписаться в Реле Модерн
Как отписаться от подписки в Relay Modern?
Я следовал учебному пособию по подписке на GraphQL React + Relay, но там не упоминается, как вы отменили подписку на сайте Relay Modern.
Любая помощь будет потрясающей.
ОБНОВИТЬ ----------
По словам Ли Байрона ( см. Выпуск GitHub), вам просто нужно позвонить dispose()
на requestSubscription()
После внесения следующих изменений в пример:
./src/subscription/NewVoteSubscription.js (Добавление return
запросить подписку)
export default () => {
const subscriptionConfig = {
subscription: newVoteSubscription,
variables: {},
updater: proxyStore => {
const createVoteField = proxyStore.getRootField('Vote')
const newVote = createVoteField.getLinkedRecord('node')
const updatedLink = newVote.getLinkedRecord('link')
const linkId = updatedLink.getValue('id')
const newVotes = updatedLink.getLinkedRecord('_votesMeta')
const newVoteCount = newVotes.getValue('count')
const link = proxyStore.get(linkId)
link.getLinkedRecord('votes').setValue(newVoteCount, 'count')
},
onError: error => console.log(`An error occured:`, error)
}
return requestSubscription(
environment,
subscriptionConfig
)
./src/components/LinkList.js (Настройка подписки для компонента и затем использование componentWillUnmount
в dispose()
Это)
componentDidMount() {
this.subscription = NewVoteSubscription()
}
componentWillUnmount() {
this.subscription.dispose()
}
Вот ошибка, которую я получаю:
Uncaught TypeError: Cannot read property 'dispose' of undefined
at RelayObservable.js:94
at doCleanup (RelayObservable.js:453)
at Object.unsubscribe (RelayObservable.js:474)
at RelayObservable.js:330
at doCleanup (RelayObservable.js:453)
at Object.unsubscribe (RelayObservable.js:474)
at doCleanup (RelayObservable.js:450)
at Object.unsubscribe [as dispose] (RelayObservable.js:474)
at LinkList.componentWillUnmount (LinkList.js:18)
at callComponentWillUnmountWithTimerInDev (react-dom.development.js:11123)
at HTMLUnknownElement.callCallback (react-dom.development.js:1309)
at Object.invokeGuardedCallbackDev (react-dom.development.js:1348)
at invokeGuardedCallback (react-dom.development.js:1205)
at safelyCallComponentWillUnmount (react-dom.development.js:11131)
at commitUnmount (react-dom.development.js:11421)
at unmountHostComponents (react-dom.development.js:11362)
at commitDeletion (react-dom.development.js:11392)
at commitAllHostEffects (react-dom.development.js:12279)
at HTMLUnknownElement.callCallback (react-dom.development.js:1309)
at Object.invokeGuardedCallbackDev (react-dom.development.js:1348)
at invokeGuardedCallback (react-dom.development.js:1205)
at commitAllWork (react-dom.development.js:12384)
at workLoop (react-dom.development.js:12695)
at HTMLUnknownElement.callCallback (react-dom.development.js:1309)
at Object.invokeGuardedCallbackDev (react-dom.development.js:1348)
at invokeGuardedCallback (react-dom.development.js:1205)
at performWork (react-dom.development.js:12808)
at batchedUpdates (react-dom.development.js:13262)
at performFiberBatchedUpdates (react-dom.development.js:1656)
at stackBatchedUpdates (react-dom.development.js:1647)
at batchedUpdates (react-dom.development.js:1661)
at Object.batchedUpdatesWithControlledComponents [as batchedUpdates] (react-dom.development.js:1674)
at dispatchEvent (react-dom.development.js:1884)
1 ответ
И настройте RelayEnvironment
function setupSubscription(config, variables, cacheConfig, observer) {
const query = config.text;
const subscriptionClient = new SubscriptionClient(websocketURL, {
reconnect: true
});
const client = subscriptionClient.request({ query, variables }).subscribe({
next: result => {
observer.onNext({ data: result.data });
},
complete: () => {
observer.onCompleted();
},
error: error => {
observer.onError(error);
}
});
return {
dispose: client.unsubscribe
};
}
Поскольку relay-modern@6
вам нужен return observable, иначе он выйдет из строя из-за этой ошибки: RelayObservable: Unhandled Error TypeError: source.subscribe is not a function
вместо того
return {
dispose: client.unsubscribe
};
тебе нужно вернуть
return Observable.create(() => {
// return cleanup function
return yourFunctionToCleanUp;
});
где Observable можно импортировать из relay-runtime
.
Подобно:
import {
Observable,
} from 'relay-runtime';
так когда ты позвонишь this.subscription.dispose()
в componentWillUnmount
на самом деле он вызовет функцию yourFunctionToCleanUp()
.