So I’m using Redux and we’re using React for our template. And I have come up with a pattern binding Redux and Meteor’s pub/sub.
The scenario is we have 2 Components OrderPage and CartPage that subscribe to the same publication let’s call it Carts
. Some of the data in the Carts
publication are synced to our Redux Store, perhaps let’s say we have this structure for the Carts
document:
{
_id: ...
items: ...
address: ... // Synced in Redux Store
userId: ... // Ditto
}
// I deliberate didn't sync **items** into the
// Redux Store since it's too many.
Surely we can duplicate the subscription code to both the OrderPage and the CartPage, but what if in a silly scenario we decided to create another page called ProductPage that needs to subscribe to the same publication, and another one. This will become a headache to manage if we decide that later we need to sync another field let’s say creatioDate
to the Store, we have to apply all (if our memory is good) the changes to all the affected Components.
So I’ve thought of Centralizing the sync and decided to put it right after the Store is created like so:
const store = createStore(rootReducer, initialState, enhancers);
// Syncing Meteor user to Redux so we can easily
// inject it to containers and no need to resubscribe to each component
Tracker.autorun(() => {
if (Meteor.subscribe('Carts').ready()) {
const cart = Carts.findOne()
if (cart) {
store.dispatch(syncAddress(cart))
store.dispatch(syncUser(cart))
}
}
})
The advantage of this is I don’t have to reimplement the subscription to all the Components involved. However, I’m not confident with this approach, so I’m very much open to suggestions.
Another problem with this one since I’m not syncing the items
list in the Store I still have to subscribe to all the Components concerned but this will be for another day.
PS. Sorry for the long post, I hope I made sense somehow.