The code here captures some of the patterns I used in the "real estate" demo app discussed in my talk End to End Apps with Polymer from Polymer Summit 2017.
There are many ways to connect Redux to custom elements, and this demonstrates just one pattern. The most important aspects are to try and lazily-load as much of the otherwise global state management logic along with the components that need them (as shown via the lazyReducerEnhancer
and addReducers
calls in the connected components), and to consider the tradeoffs you make in terms of coupling components to the store.
The pattern shown here of creating a stateless component and then a subclass that connects it to the store addresses a potential desire to reuse app-level stateless components between more than one application context, so the subclass provides a degree of decoupling from the concrete store, at the expense of more boilerplate. If app component portability is not a constraint you need, you could just connect components directly and avoid the subclass & potentially unnecessary added event dispatching overhead. The stateless/connected pattern also allows the stateless component to be connected to alternative state management systems as well.
Likewise, there are pros/cons to having many "connected" components, vs. e.g. just the top-level app component having the binding to the store. In the former case (many connected components), you avoid the need to bind properties down the tree as elements can pull their property values directly out of the store, but at the cost of more components tightly-coupled to the store and loss of tree context that you gain with the latter approach (one connected component, with all other components receiving properties via data binding).
It's difficult to declare a "one-size-fits-all" approach, so I'd recommend trying to understand the approaches and tradeoffs and make a good judgement for your application scenario. Once the full polymer-re
app is cleaned up enough to be a good "demo app" that folks can copy/paste from, I do plan to open source it, and we may roll some of these patterns into future application templates as well.
Note: These examples are mildly pseudo-codey and assume an ES module context and some ES Next features (object spread) -- the main point is to convey the concepts. The concepts still apply e.g. using HTML imports and loading Redux using a UMD build via a global.
Much like the
react-redux
the mapping of the events and state is done through a connector, which is the same as a container in React. Working with the two libraries (Polymer, React) this gives it a more consistent feel of binding Redux. Jumping between the two I think developers will quickly know how to bind due to the similarities.The lazy loading of reducers is also a nice addition.
I might use your approach to create
<redux-connector>
element forpolymer-redux
that not only achieves the bindings but also has the ability to add reducers.Thanks for sharing 👍