- author: CodeDonor
Implementing a Bundles Reducer in Redux
We've established that we want to implement a bundles reducer in our Redux application. Before we begin writing any code, let's take a step back and think about the implementation and design of this bundles piece of state. Here's what we need to consider:
Diagram of Sales and Bundles State
We need to have a clear understanding of the structure of our sales and bundles piece of state. In a typical Redux store, the sales state could be an object with information about the current sales, while the bundles state could also be an object where the keys are the ID of a particular cell and the values are the bundled output.
Handling User Inputs
Whenever a user types into our code editor, we are currently dispatching an action of type 'update cell' which updates the content of a particular cell in our cells reducer. However, we don't want to tie our bundles piece of state directly to this update cell action.
Debouncing Logic
We have to consider debouncing logic inside our Redux store. We want to avoid rebundling the user's code with every single keypress that can drain power from mobile devices or laptops. One option could be to add a new action creator to update the bundle, but given that we want to handle the middleware in Redux, this solution is not ideal.
Choosing the Right Solution: Bundler Middleware
We want to make use of the middleware feature in Redux, which is a perfect use case for the problem we are trying to tackle. Here's how we'll do it:
- Whenever a user types into the code editor, we'll dispatch the 'update cell' action creator instantly.
- We'll have a bundles middleware that will run whenever it receives an action. It will also implement debouncing logic, setting up a timer to bundle the user's code after an arbitrary period.
- If the time elapses, the middleware will bundle the user's code and then dispatch another action to capture it in the bundles reducer.
- If a user types twice quickly, two 'update cell' actions will be dispatched, but the middleware will reset the timer to bundle the code before it completes and so on with every subsequent keystroke.
This solution allows any action to pass through and be forwarded immediately while also implementing debouncing logic that bundles the user's code and updates the bundles state.
Conclusion
Before implementing a bundles reducer in your Redux application, it's crucial to take some time to think about the design and implementation of the bundles piece of state. By utilizing the bundler middleware, we can avoid tying our bundles state to the update cell action and implement debouncing logic. With this solution, we can update our bundles state efficiently while avoiding overloading our user's devices.