Hey guys, this post is dedicated to our recent conference presentation about using MobX in angular. We will cover following points in the article:
- What is state management and how to make it painless
- Classic observer-observable patterns and how MobX uses it
- How to apply MobX in angular application
- Couple of MobX tricks to know
State Management
What is state management? As you might know or guess application state means all current information and data, which is essential to the application and affect visual part of application. Any UI change, user actions, buttons clicks and so on change the state of application. And this means, that application should update other UI parts and components, to keep itself consistent with the state.
The ancient approach of dealing with it - manual implementation of every actions in javascript (assuming we talking about web applications). It leads to tons of javascript code, click handlers and complexity of change and refactoring.
This is exact point where all familiar with Angular 2+ people should scream and shout that Angular is clever enough to handle all that by itself. And yes it is. But only in case of default change detection strategy, when Angular updates everything every time. If you have rather small application - go with it. But in case if application is big enough, you have bunches of UI components to show a lot of data, you might notice performance overhead and some slowness. And still data relations will be unclear from the code.
This leads us to look into state management approaches, like MobX. Such libraries (or you can think of it more like design pattern) force us to think in terms of data and it’s relations, rather than code. These kind of approaches brings more structure to UI code, makes refactoring easier and getting into the project faster. I would like to mention performance as well in some cases. When you use OnPush strategy in angular, it will not update UI components every time. Please check out article with more details by link at end of this post. And MobX will help Angular a little bit, putting needed components to list for update during next change detection.
Observer-Observable Pattern
This is classical pattern, simple and powerful enough. Let’s take a look at the picture.
It has so called ‘Observable’, which is essentially our state, but with some additions. Other entities can ‘subscribe’ to it’s changes. ‘Observable' entity handles the list of it’s subscribers, and when value changes, ‘Observable’ iterates list of ‘observers’, calling method ‘handleChanges’ for each.
In fact it very easy to explain in excel sheet terms. There is data cell and formula cell. Data cell is ‘Observable’, formula - ‘observer’. Data cell knows which formula cells uses it. When value changes, this cell notifies every dependent formula and asks to re-calculate.
MobX in Angular
Perform these actions to integrate MobX in Angular application:
- install needed dependencies:
- Import MobX module to your Angular application module
- Set ChangeDetectionStrategy.OnPush for your components. MobX library makes sense only with OnPush strategy.
- Set this attribute for html components in template, which should be updated by MobX-Angular: *mobxAutorun="{dontDetach: true}"
Detach / Don't Detach
Additional setting dontDetach is not documented feature of MobX, needed for Angular applications. And this is a bit confusing, because different parts of MobX-Angular documentation contradict to each other.
The idea is, that you can use just *mobxAutorun attribute. But for performance reasons you can use it with parameters {{detach = true} for example) or use OnPush strategy. This means, that component will be detached from Angular change detection and behave on it's own. But according to experience, it might cause component not to be updated in some cases, especially when component structure is complicated. That's why in prod applications we use both OnPush and {dontDetach = true}.
- Use these attributes in your typescript classes to mark data and functions: @observable, @computed, @action
Store Architecture approach
Suggested Store approach to use with MobX is like described in a picture. Let’s dive in a little bit. We applied such pattern in several production projects.
Each Angular component has View (html template), component class and store. This store contains observable variables and other MobX stuff, needed for particular component only. This leads to clear separation of data logic and everything else. Store contains only code and declarations, which are related to application state.
View of the component (or any of component’s parents) should contain MobX attribute:
It’s enough to put this attribute on top of all components, but usually it makes sense to put it only in parts, which requires MobX observing.
Component class is regular Angular component:
And Store contains @observable declarations:
Also we can have data stores, which could be used in several other stores or components as sources of data.
Store classes can have:
- @observable decorators for variables. When you put this decorator, MobX will wrap this variable into get/set code, with additional logic. When data is changed, MobX knows this and can call all ‘observers’ of this data to refresh. When you assign value to some UI component (which is under *mobxAutorun attribute of course), MobX puts this component into list of ‘observers’.
- @computed decorator is used for get functions only. This concept is similar to excel formula. For example, when you want to use some filtered data (and possibly map as well) in UI, you can incapsulate all filtering and mapping logic into @computed get function. You can also use several @observables in @computed function. When any of dependent observables have been changed, computed function will be recalculated. And the good thing is, that it will be recalculated only once per any of observables change because of caching.
- @action decorator is used for any function, where you will change value of observable.
Good thing about MobX is that it’s designed to let you use classes and properties for observable variables with any depth or arrays. Change of data can look like this:
Or
MobX is looking for such changes and accepts mutable state strategy. In other words, MobX expect that you will actually change values of existing @observable variables or it’s inner properties.
MobX tricks to know
You might need these small things to be equipped with when using MobX:
- you can use debug console to track all MobX actions and reactions by entering this command in browser console: mobxAngularDebug(true)
- Use extendObservable function to add new property of observable object, when it’s already in use of MobX
- Use toJS function to get clear java script object (for console log for example)
- Try to use minimum amount of .filter and .map in @computed get functions to keep code readable and debuggable.
- Just don’t forget that @observable !== Observable<any> from RxJS</any>
Helpful links
In English
- MobX documentation
- Redux in Angular
- MobX vs Redux podcast
- MobX in Angular article
- MobX-Angular Github readme
- Sample Project in GitHub You can clone it and play with Angular + MobX application
In Russian
Thank you and see you on our meet-ups!
Billing Automation for a SaaS Company with Low-Code
Our client needed a robust billing solution to manage hierarchical licenses, ensure compliance, and automate invoicing for streamlined operations.
The solution:
We developed a Retool-based application that supports multi-tiered licenses, automates invoicing workflows, and integrates seamlessly with CRM and accounting platforms to enhance financial data management.
The result:
- Achieved 100% adherence to licensing agreements, mitigating penalties.
- Automated invoicing and workflows reduced manual effort significantly.
- Dashboards and reports improved decision-making and operational visibility.
Retool Dashboards with HubSpot Integration
Our client needed a centralized tool to aggregate account and contact activity, improving visibility and decision-making for the sales team.
The solution
We built a Retool application integrated with HubSpot, QuickMail, and Clay.com. The app features dashboards for sorting, filtering, and detailed views of companies, contacts, and deals, along with real-time notifications and bidirectional data syncing.
The result
- MVP in 50 hours: Delivered a functional application in just 50 hours.
- Smarter decisions: Enabled data-driven insights for strategic planning.
- Streamlined operations: Reduced manual tasks with automation and real-time updates.
Lead Generation Tool to Reduce Manual Work
Our client, Afore Capital, a venture capital firm focused on pre-seed investments, aimed to automate their lead generation processes but struggled with existing out-of-the-box solutions. To tackle this challenge, they sought assistance from our team of Akveo Retool experts.
The scope of work
The client needed a tailored solution to log and track inbound deals effectively. They required an application that could facilitate the addition, viewing, and editing of company and founder information, ensuring data integrity and preventing duplicates. Additionally, Afore Capital aimed to integrate external tools like PhantomBuster and LinkedIn to streamline data collection.
The result
By developing a custom Retool application, we streamlined the lead generation process, significantly reducing manual data entry. The application enabled employees to manage inbound deals efficiently while automated workflows for email parsing, notifications, and dynamic reporting enhanced operational efficiency. This allowed Afore Capital's team to focus more on building relationships with potential founders rather than on administrative tasks.
Retool CMS Application for EdTech Startup
Our client, CutTime, a leading fine arts education management platform, needed a scalable CMS application to improve vendor product management and user experience.
The scope of work
We developed a Retool application that allows vendors to easily upload and manage product listings, handle inventory, and set shipping options. The challenge was to integrate the app with the client’s system, enabling smooth authentication and product management for program directors.
The result
Our solution streamlined product management, reducing manual work for vendors, and significantly improving operational efficiency.
Building Reconciliation Tool for e-commerce company
Our client was in need of streamlining and simplifying its monthly accounting reconciliation process – preferably automatically. But with a lack of time and low budget for a custom build, development of a comprehensive software wasn’t in the picture. After going through the case and customer’s needs, we decided to implement Retool. And that was the right choice.
The scope of work
Our team developed a custom reconciliation tool designed specifically for the needs of high-volume transaction environments. It automated the processes and provided a comprehensive dashboard for monitoring discrepancies and anomalies in real-time.
The implementation of Retool significantly reduced manual effort, as well as fostered a more efficient and time-saving reconciliation process.
Creating Retool Mobile App for a Wine Seller
A leading spirits and wine seller in Europe required the development of an internal mobile app for private client managers and administrators. The project was supposed to be done in 1,5 months. Considering urgency and the scope of work, our developers decided to use Retool for swift and effective development.
The scope of work
Our developers built a mobile application tailored to the needs of the company's sales force: with a comprehensive overview of client interactions, facilitated order processing, and enabled access to sales history and performance metrics. It was user-friendly, with real-time updates, seamlessly integrated with existing customer databases.
The result? Increase in productivity of the sales team and improved decision-making process. But most importantly, positive feedback from the customers themselves.
Developing PoC with Low Code for a Tour Operator
To efficiently gather, centralize, and manage data is a challenge for any tour operator. Our client was not an exception. The company was seeking to get an internal software that will source information from third-party APIs and automate the travel itinerary creation process. Preferably, cost- and user-friendly tool.
The scope of work
Our experts ensured the client that all the requirements could be covered by Retool. And just in 40 hours a new software was launched. The tool had a flexible and easy-to-use interface with user authentication and an access management system panel – all the company needed. At the end, Retool was considered the main tool to replace the existing system.
Testing New Generation of Lead Management Tool with Retool
Our client, a venture fund, had challenges with managing lead generation and client acquisition. As the company grew, it aimed to attract more clients and scale faster, as well as automate the processes to save time, improve efficiency and minimize human error. The idea was to craft an internal lead generation tool that will cover all the needs. We’ve agreed that Retool will be a perfect tool for this.
The scope of work
The project initially began as a proof of concept, but soon enough, with each new feature delivered, the company experienced increased engagement and value.
We developed a web tool that integrates seamlessly with Phantombuster for data extraction and LinkedIn for social outreach. Now, the company has a platform that elevates the efficiency of their lead generation activities and provides deep insights into potential client bases.
Building an Advanced Admin Portal for Streamlined Operations
Confronted with the need for more sophisticated internal tools, an owner of IP Licensing marketplace turned to Retool to utilize its administrative functions. The primary goal was to construct an advanced admin portal that could support complex, multi-layered processes efficiently.
The scope of work
Our client needed help with updating filters and tables for its internal platform. In just 30 hours we've been able to update and create about 6 pages. Following features were introduced: add complex filtering and search, delete records, styling application with custom CSS.
Together, we have increased performance on most heavy pages and fixed circular dependency issues.
Creating MVP Dashboard for Google Cloud Users
Facing the challenge of unoptimized cloud resource management, a technology firm working with Google Cloud users was looking for a solution to make its operations more efficient. The main idea of the project was to create an MVP for e-commerce shops to test some client hypotheses. Traditional cloud management tools fell short.
The scope of work
Determined to break through limitations, our team of developers turned Retool. We decided to craft an MVP Dashboard specifically for Google Cloud users. This wasn't just about bringing data into view; but about reshaping how teams interact with their cloud environment.
We designed a dashboard that turned complex cloud data into a clear, strategic asset thanks to comprehensive analytics, tailored metrics, and an intuitive interface, that Retool provides. As the results, an increase in operational efficiency, significant improvement in cost management and resource optimization.
Elevating CRM with Custom HubSpot Sales Dashboard
Our other client, a SaaS startup, that offers collaborative tools for design and engineering teams, was on a quest to supercharge their sales efforts. Traditional CRM systems were limited and not customizable enough. The company sought a solution that could tailor HubSpot to their workflow and analytics needs.
The scope of work
Charged with the task of going beyond standard CRM functions, our team turned to Retool. We wanted to redefine how sales teams interact with their CRM.
By integrating advanced analytics, custom metrics, and a user-friendly interface, our developers provided a solution that transformed data into a strategic asset.
In 40 hours, three informative dashboards were developed, containing the most sensitive data related to sales activities. These dashboards enable our customer to analyze sales and lead generation performance from a different perspective and establish the appropriate KPIs.
Building a PDF Editor with Low-Code
Our client, a leading digital credential IT startup, needed a lot of internal processes to be optimized. But the experience with low-code tools wasn’t sufficient. That’s why the company decided to hire professionals. And our team of developers joined the project.
The scope of work
The client has a program that designs and prints custom badges for customers. The badges need to be “mail-merged” with a person’s info and turned into a PDF to print. But what is the best way to do it?
Our developers decided to use Retool as a core tool. Using custom components and JavaScript, we developed a program that reduced employees' time for designing, putting the data, verifying, and printing PDF badges in one application.
As a result, the new approach significantly reduces the time required by the internal team to organize all the necessary staff for the conference, including badge creation.