Suppose I have two react components.
Component A is an e-commerce store a site owner can add to their site. This holds the stores products, and visitors to the site can select items to add to a shopping cart.
Component B is a shopping cart component, that a site owner can choose to add to the header of their site.
A basic use case that I would like to solve is as follows:
- A user visits the site and adds an item to their cart
- Component A executes an action to update a shared Cart store
- This Cart store alerts component B to the change
- Component B updates its state by grabbing the new Cart info from Cart store
- The new count is reflected in the header
On the site, components like A and B are called 'addons'. When the main site renders its page, it runs through a list of addons to render on the page. Each of these addons are independent of one another.
My question is, is there any way for two of these addons to be passed the same store, or subscribe to the same store, without interaction from the main, parent component?
If this is not possible, my next solution is to house components A and B in a container component X. X would be a provider holding the state and business logic. A and B would merely contain the view logic. X would render as an addon, but be invisible on the page, and manage the states of A and B.
If I went with this container approach, is there any way to extract A and B from the container so I can render them independently once they are linked up to the same store?
I have done something like this using ReactJS using both Reflux or Redux (which I recommend more).
Essentially I would separate the cart and the e-commerce store into two smart or container components that would have direct contact with the Redux Store.
In Redux, we have one data Store, but we can have multiple reducers (basically immutable objects inside the store).
This would be the flow:
1) User adds product to shopping cart by clicking a product. 2) Component A sends an action to update the cart 3) The Redux Store is updated with a shopping cart item and this triggers the shopping cart to add a new item to the Component B because we have just added an a new object to the Store. this.state = { shoppingCartItems: [{id: 1, name: item1, price: $29.00} ] }
Essentially, in Redux you would have two reducers in one Store. One for the store (keeps track of all the products) and one for the shopping cart (keeps track of all current items added).
Here's another Redux example, you can get inspiration from that is a shopping cart example
https://github.com/reactjs/redux/tree/master/examples/shopping-cart