matrix-react-sdk icon indicating copy to clipboard operation
matrix-react-sdk copied to clipboard

Store refactor: use non-global stores in components

Open kegsay opened this issue 3 years ago • 5 comments

This is part of a series of PRs aiming to improve stores. This PR focuses on a pattern for passing stores to components in a way that doesn't involve global singletons.

Added a new kind of class:

  • Add God object Stores which will hold refs to all known stores and the MatrixClient. This object is NOT a singleton.
  • Add StoresContext to hold onto a ref of Stores for use inside components.

StoresContext is created via:

  • Create Stores in MatrixChat, assigning the MatrixClient when we have one set. Currently sets the RVS to RoomViewStore.instance.
  • Wrap MatrixChats render() function in a StoresContext.Provider so it can be used anywhere.

StoresContext is currently only used in RoomView via the following changes:

  • Remove the HOC, which redundantly set mxClient as a prop. We don't need this as RoomView was using the client from this.context.
  • Change the type of context accepted from MatrixClientContext to StoresContext.
  • Modify alllll the places where this.context is used to interact with the client and suffix .client.
  • Modify places where we use RoomViewStore.instance and replace them with this.context.roomViewStore.

This makes RoomView use a non-global instance of RVS.

Checklist

  • [ ] Tests written for new code (and old code if feasible)
  • [ ] Linter and other CI checks pass
  • [ ] Sign-off given on the changes (see CONTRIBUTING.md)

This change is marked as an internal change (Task), so will not be included in the changelog.

kegsay avatar Sep 16 '22 14:09 kegsay

Agreed the name Stores could be better. I would strongly push for it to be a "general stuff-you-need context" else you end up designing situations where a component may need >1 context which then needs HOC to do and it ends up being more boilerplate for little gain. ReactSDKContext is better but a bit long and probably redundant (given it's a React.Context we needn't mention React, so maybe SDKContext?)

kegsay avatar Sep 16 '22 14:09 kegsay

SDKContext sounds sensible to me, fwiw.

ara4n avatar Sep 17 '22 12:09 ara4n

Please avoid force-pushing as it makes review harder by not allowing commit-by-commit reviewing

t3chguy avatar Sep 21 '22 09:09 t3chguy

The force push was done to rebase this PR off develop rather than #9290 - sorry about that. There were no additional code changes.

kegsay avatar Sep 21 '22 10:09 kegsay

Given we squash merge PRs, you can just merge commit instead of rebasing in most cases

t3chguy avatar Sep 21 '22 10:09 t3chguy

Force merging due to regex refactor not needing as much coverage

t3chguy avatar Oct 19 '22 12:10 t3chguy