fix: fixed subscriptions for token balances #374
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
In current implementation, we are creating a query subscriptions in the effect hook of the App component to listen for balance changes. Subscription callback functions are depending on the global redux state which they also modify. Therefore a callback has to be modified when the balance state changes. However, we are not able to modify the callback of existing subscriptions and can only create new query subscription with different callback because of the limitations imposed by the polkadot.js api package.
The problem of current implementation is that we are creating new subscription with modified callback with each state change, but are not closing the previous subscriptions. As a result, ever-increasing amount of subscriptions is created with each run of the effect hook which ends up freezing the whole dApp: with each balance change all of these subscriptions are calling the redux reducers which changes the redux state and triggers creation of new subscriptions.
To solve this issue, I moved the callbacks for unsubscribing into React refs and added a call to unsubscribe each time when new subscription is created (not only when the component is unmounted). Also, I split the hook into 3 data-specific ones to enforce that new subscription is created only when related data change.
Note: Ideal solution would be to create subscription on the first render only and then just modify the callback function, but that is not possible now, because the
@polkadot/api
does not expose this functionality.