Blog Feed Post

From a convenience store to Redux architecture

Imagine that you’re a proud owner of a convenience store that sells various products. Remember how did you start? You rented an empty place (i.e. the store was in its initial state). Then you purchased shelves and ordered products. After that, multiple vendors started delivering products. You hired employees that arranged these products on the shelves in a certain order changing the state of the store. Then you put out the Grand Opening sign and lots of colorful balloons.

Customers started visiting your store and buy products. When the store is open, some products lay on the shelves, and some products are in the shopping carts of customers. Some customers are waiting in lines at the cash registers, and there are store employees there. In other words, we can say that at any given moment, your store has the current state.

If a customer takes an action, e.g. buys five bottles of water, the cashier scans the barcodes, which reduces the number of bottles in the inventory, i.e. updates the state. If a vendor delivers new products, your clerk updates the inventory (i.e. state) accordingly.

Your web app can also maintain a store that holds the state of your app. Similarly to a real store, at any given time your app’s store has a current state. Some data collections have specific data retrieved from the server and, possibly modified by the user. Some radio buttons are checked, the user selected some products and navigated to some routes represented by a specific URL.

If the user interacts with the UI, or the server sends new data, these actions should ask the store object to update the state. But to keep track of the state changes, the current state object is never updated, but a new instance of the state object is created.

What’s Redux?

Redux an open-source JavaScript library that takes care of managing application state. Initially, the React.js developers made Redux popular, but since it’s just a library for maintaining an app state, it can be used in any JavaScript app. Redux is based on the following three principles:

  • Single source of truth. There is a single store where your app contains the state that can be represented by an object tree.
  • State is read-only. When an action is emitted, the reducer function won’t update, but clone the current state and update it based on the action.
  • State changes are made with pure functions. You write the reducer function(s) that takes an action and the current state object, and returns a new state.

In Redux, the data flow is unidirectional:

1. The app component dispatches the action on the store
2. The reducer (a pure function) takes the current state object and then clones, updates, and returns it.
3. The app component subscribes to the store, receives the new state object and updates the UI accordingly.

This is how the Redux unidirectional data flow can be presented if used in a web app.

https://yakovfain.files.wordpress.com/2018/02/ch15_redux_flow.png?w=1520... 1520w, https://yakovfain.files.wordpress.com/2018/02/ch15_redux_flow.png?w=150&... 150w, https://yakovfain.files.wordpress.com/2018/02/ch15_redux_flow.png?w=300&... 300w, https://yakovfain.files.wordpress.com/2018/02/ch15_redux_flow.png?w=768&... 768w, https://yakovfain.files.wordpress.com/2018/02/ch15_redux_flow.png?w=1024... 1024w" sizes="(max-width: 760px) 100vw, 760px" />

An action is a JavaScript object that has a property `type` describing what happened in your app, e.g. the user wants to buy the IBM stock. Besides the property type, and action object can optionally have another property with the payload of data that should somehow change the app state, for example:

  type: 'BUY_STOCK',
  stock: { symbol: 'IBM', quantity: 100} 

This object only describes the action and provides the payload, but it doesn’t know how the state should be changed. Who does? The reducer.

A reducer is a pure function that specifies how the state should be changed. The reducer never changes the current state but creates a new (and updated) version of it. In other words, the state object is immutable. The reducer creates a copy of the state object and returns a new reference to it. If you use the Angular framework, it’s a binding change event, and all interested parties will immediately know that the state has changed without requiring expensive value checking in the entire state tree.

A reducer function has the following signature:

function (previousState, action): State {...} 

Should the reducer function implement the app functionality like placing an order, which requires work with external services? Of course not, because reducers are meant for updating and returning the app state, e.g. the stock to buy is “IBM”. Besides, implementing the app logic would require interaction with the environment external to the reducer, i.e. it would cause side effects, and pure functions can’t have side effects.

The reducer can implement minimal app logic related to the state change. For example, the user decides to cancel the order, which requires a reset of certain fields on the state object. The main app logic remains in your application code (e.g. in services) unless a concrete implementation of the Redux-inspired library offers a special place meant for the code with side effects.

Why storing an app state in a single place is important

Recently, I was working on a project for a car manufacturer. This was a web app that allowed a prospective buyer to configure a car by selecting from tons of packages and options (e.g. model, interior and exterior colors, length of the chassis et al.) This app was developed for many years, the software modules were written using JavaScript, jQuery, Angular, React, Handlebars as well as the HTML templating engine Thymeleaf on the server.

From the user’s perspective, this was one workflow that consisted of several steps resulting in configuring and pricing the car based on selected options. But internally, this process was switching from one module to another, and each module would need to know what was selected in the previous step to show the available options.

In other words, each module would need to know the current state of the app. Depending on the software used in any particular module, the current user’s selections were stored using one of the following places:

* URL parameters
* HTML data attributes
* Browser’s local and session storages
* Angular services
* React store

Time and time again, this was turning implementing a seemingly simple new requirement into a very time consuming and expensive task. Re-writing an app from scratch was not an option, but it would be so much easier if the app state was implemented in a uniform way and stored in a single place.

While the Redux is widely used in the web apps developed with the React framework, for Angular apps you can use the ngrx library that also implements the unidirectional data flow and can be used for implementing the app state management.
While the Redux API is simple, the ngrx is not. The reason is that ngrx is a combination of Redux and RxJS libraries that offers more than just keeping track of the round-trips between the UI and the app state. With ngrx, you can inject the code that communicates with external services into the data flow. Also, you can monitor the state of the router.

I’m planning to write a series of blogs to present ngrx, so it wouldn’t require a Ph.D. to master it. If you can’t wait, consider enrolling in our online workshop on using ngrx for state management in Angular apps. You’ll need to invest 7 hours of your time, but this may save you a lot more time in the long run.

Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Latest Stories
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Evan Kirstel is an internationally recognized thought leader and social media influencer in IoT (#1 in 2017), Cloud, Data Security (2016), Health Tech (#9 in 2017), Digital Health (#6 in 2016), B2B Marketing (#5 in 2015), AI, Smart Home, Digital (2017), IIoT (#1 in 2017) and Telecom/Wireless/5G. His connections are a "Who's Who" in these technologies, He is in the top 10 most mentioned/re-tweeted by CMOs and CIOs (2016) and have been recently named 5th most influential B2B marketeer in the US. H...
How is DevOps going within your organization? If you need some help measuring just how well it is going, we have prepared a list of some key DevOps metrics to track. These metrics can help you understand how your team is doing over time. The word DevOps means different things to different people. Some say it a culture and every vendor in the industry claims that their tools help with DevOps. Depending on how you define DevOps, some of these metrics may matter more or less to you and your team.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
@DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises - and delivering real results.
DXWorldEXPO LLC announced today that Dez Blanchfield joined the faculty of CloudEXPO's "10-Year Anniversary Event" which will take place on November 11-13, 2018 in New York City. Dez is a strategic leader in business and digital transformation with 25 years of experience in the IT and telecommunications industries developing strategies and implementing business initiatives. He has a breadth of expertise spanning technologies such as cloud computing, big data and analytics, cognitive computing, m...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
DXWorldEXPO LLC announced today that Kevin Jackson joined the faculty of CloudEXPO's "10-Year Anniversary Event" which will take place on November 11-13, 2018 in New York City. Kevin L. Jackson is a globally recognized cloud computing expert and Founder/Author of the award winning "Cloud Musings" blog. Mr. Jackson has also been recognized as a "Top 100 Cybersecurity Influencer and Brand" by Onalytica (2015), a Huffington Post "Top 100 Cloud Computing Experts on Twitter" (2013) and a "Top 50 C...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...