Asked By: Anonymous
I’m importing a newed up subject from an internal NPM package into my Next.js application.
Internal NPM Package
import { Subject } from 'rxjs';
export const errorSubject = new Subject<{}>();
Next.js App
import { errorSubject } from '@my-package'
// Inside component's render
render() {
errorSubject.subscribe({
next: v => console.log(v),
});
}
Everytime the Next.js hot-reloads, a new subscription is created. If I reload the pages, only 1 subscription remains.
This is causing issues because multiple callbacks are ran.
https://www.youtube.com/watch?v=cqy3RPQocRw
Solution
Answered By: Anonymous
Save a reference to your subscription so everytime you unmount the component you get rid of it.
private _subscription;
render() {
this._subscription = errorSubject.subscribe({
next: v => console.log(v),
});
}
componentWillUnmount() {
this._subscription.unsubscribe();
}