State management of angular 2 application - javascript

I am new in Angular2. Angular provides various options for managing the state of an application like ngrx/store, angular services etc. if we manage the state of the application using ngrx/store then we require an external library but in case of angular services do not require. What should be used for managing the state of an application? what are the pros and cons of each approach? Is there any recommendation that is provided by the angular community?

You do not need ngrx/store to implement a redux-store. You can implement one yourself. There are multiple tutorials online showing how to do it in a lightweight way. But ngrx/store is developed and supported by people from google and so it is a mature framework you can trust, which also provides some neat features, like effects for asynchronous events and immutability checks in development.
The main question is whether or not you should use the redux pattern/store in general. This highly depends on your application architecture. For smaller applications it could be too much work, especially if you don't have clear user stories and things might change quickly.But i f you have a big SPA, in general it is recommended to use a central data flow store, e.g. redux. It ensures the dataflow in your application is unidirectional and there are no circular dependencies at important parts of your application, causing weird bugs in the future as your application gets more complex.
Also even in a SPA you have things like UI-Libraries which do not belong in a store. A button prototype being enabled or disabled is something only its component should be aware of. But the same button in usage in the application module should represent a particular functionality being offered or not and that should be represented in redux.
I highly suggest you look at the ngrx-store example app and see the benefits and shortcomings yourself.

Related

When ReactJs is appropriate

From what I have been researching, ReactJS is the new craze in the world of front-end development. I can find few articles that are able to provide a bias free look on ReactJS. There is only praise for it, but should it be used everywhere? I know an html.erb file with javascript can accomplish what ReactJS can do. Everything has its place. Where does ReactJS and React Native fit in? Specifically when should they be used? I know JavaScript can handle a lot, but of those things it probably shouldn't handle, or there is a better solution.
I would greatly appreciate guidance on these questions.
React has many cool features and is one of the best libraries for using for building UI apps
it utilizes something called the virtual dom to enhance performance in applications
it has a really intuitive pattern with storing state in local components which can be passed down to children components as props.
it integrates well with state management frameworks like Redux (there is a helper package called react-redux which makes the integration seamless) but it also has it's own context API which can be used for wider ranging state
it recently introduced the concept of hooks. these replaced lifecycle methods which were popular in previous versions and are now a cool way to "hook" into components and utilise functionality whilst the component mounts and unmount
of course, like with everything, there are alternatives. you can just use plain old vanilla which has it's own benefits or you can choose a popular alternative such as Vue.js.
There is no hard and fast rule specifically when it should be used. the ball is in your court

MVVM architectural pattern for a ReactJS application

I'm a semi-senior react and JavaScript developer, I've made several Universal react application.
Today our CTO told me: Do you use a software architectural pattern for your application?
I've no answer, He points to the Android team which use MVVM for their applications.
I'm searching greedy but not found a trend methodology or example for this situation. I've used Redux, Redux-Saga, React-Context and etc.
I don't know how to explain to our CTO or what is his answer?
Hence: Does a react app really need a software architectural pattern?
React itself is not particularly opinionated about software architecture. It is a library that facilitates the reusable component paradigm alongside guidelines for managing things like state and data sharing (props). At some point, Facebook described this as the V in MVC but have since moved away from that marketing to call it more abstractly A JavaScript library for building user interfaces.
Of course, the typical tooling associated with React apps does lend itself to something of an architecture when used together.
A couple of potential ways to think about it:
Simple React apps might be just "VVM" or "VC"
MVC is probably the better-known of the two in the development world. The key conceptual difference between a controller (C) and view-model (VM) could be boiled down into: a controller can have many diverse responsibilities, like listening for events and routing them in the right direction. It's the glue that facilitates the functionality of an entire application. A view-model, on the other hand, is simply responsible for gluing the current state of the data to the model.
So Facebook's original use of "V in MVC" could probably just as easily have been "V in MVVM" - the term controller makes more sense in backend development world.
A barebones React app, without Redux, that pulls data directly into components (e.g. fetch's in componentDidMount or leveraging GraphQL) with limited data wrangling of any kind could be called a simple "VVM" model.
View-Model (VM): Component-related code that manages simple state, passes data directly onto View, potentially passes data directly back from View
View (V): How the visuals look (JSX, CSS)
Add some complexity, and you could call it "MVVM"/"MVC"
If you toss in Redux, redux-saga, or even start doing crazy things with simple React component state, you're introducing model operations. There're at least two things this Model (M) can represent:
Actual business logic for your application
Storing and managing complex behavior in your client
Business logic is sometimes undesirable in practice: for example, if you have control over the server, it might be worth keeping all your business logic in one place (on the server) and just feed the UI what it needs to interact with the user. But if you have limited REST endpoints and need to do some wrangling (e.g. in your sagas, or within components), that'll be business logic.
Client behavior management is likely, especially in complex applications where you might be doing things like displaying different things to the user based on their session (e.g. they're an unregistered user vs. user vs. admin). You're probably doing this in any redux store interactions that are contained to use by only the client.
Disclaimer: discussing MVC, MVVM, etc. is likely to lead to many different opinions of exactly what they mean [1]. Above, I tried to draw parallels between common patterns I've seen and how they fit into MVC/MVVM, but there's so many different ways to approach it or more granular ways to think about it. I wouldn't get too hung up on putting a label on it as long as your system is easy to understand: modular, DRY, abstracted, etc. at levels that make sense for your use case and scale of development.
[1] Discussed in the some more length in answers and comments to this question
Vue 3 is MVVM:
Proxy Update
Model → ViewModel → View
Model ← ViewModel ← View
Update Event
And React:
setState Update
Model → ViewModel → View
Model ← ViewModel ← View
Update Event
The difference is only how the frameworks notify Model changes to the ViewModel.
A simple Web App does not require MVC, MVVM, does not require even React IMO.
Possible evolution of a simple ReactJS App that may see the need of MVVM/MVC/ if it tries to be PWA (Progressive Web App). In other words - if it tries to do some (application/domain) specific logic - offline and some other - online. This is natural point of thinking for mobile app development. Then, the information may be retrieved from the Local Storage or the IndexedDB (for the Web) or the Back-End/Rest/. Then, the separation of Model, Storage/Repository/Source Of INfo/ ViewModel/ or Controller/ and View will be natural and actually needed for all stuff to work correctly...

Is it common use case to use Angular 4 or React to build sections of a website?

I have to start by saying that I studied Angular 4 but I have not used it for any real projects and I don't know nothing about React. With so many technologies available I feel a little confused on when and how to use them. I have a website that I built using asp.net core. The website is a store that shows objects for sale and enable users to add and modify their products. The site is a MPA that eventually (not to say often) uses Ajax to make the application more dynamic and fast to load. I was thinking about turning the control panel that enables users add/modify their products, and uses a lot of javascript/jquery code to support those tasks, into SPA using React or Angular to make the website navigation more pleasant. Is this approach of using React and Angular in a section of website a good idea or Angular or React should only be used on the entire site?
Yes, you can combine React or Angular components with just regular website, especially when you want to rework complicated logic, which is better to do with such frameworks. You can also see how it works in action, reworking small components and decide if it worth.
I wouldn't say that it is a common practice, combining Angular 4 with React or the other way around. It is true that you can use React components in a Angular application but not the other way around.
Its really something you have to consider for yourself, usually you decide to take full advantage of a specific framework. Personal preference and or the preference of the people you are working with usually determine this.
All of this is very much based on ones own opinion.

Is Flux a library which operates as the backend for React?

I'm very new to the React and Flux consept and I'm confused as hell..
I come from a background of Sails.js so I can't really tell whats what with React.
I plan to use Sails.js (as a restful api, isolated from the front end)
+
React (as my front end using restful calls + perhaps websockets to communicate with sails)
but I don't see where flux fits in!
No.
Flux is a design pattern, rather than a framework or library. You can use Flux without using React and vice versa, although they are optimized to work well with each other.
Flux applications have three major parts: the Dispatcher, the Stores, and the Views (not be confused with Model-View-Controller). EventEmitter is typically used as a basis for Stores and React as a basis for Views. The one piece of Flux not readily available elsewhere is the Dispatcher, although you could write one yourself if you want.
Controllers do exist in a Flux application, but they are controller-views -- Views often found at the top of the hierarchy that retrieve data from the stores and pass this data down to their children. Additionally, action creators — dispatcher helper methods — are often used to support a semantic dispatcher API.
Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with a React view, the view propagates an Action through a central Dispatcher, to the various Stores that hold the application's data and business logic, which updates all of the views that are affected. While you don't need React to implement this pattern per se, it is designed to work especially well with React's declarative programming style, which allows the store to send updates without specifying how to transition views between states.
More info can be found at the official Flux repo.
Flux is definitely not a requirement for using React and does not operate as a "back-end" for React. It's just a common pattern for structuring applications written with React. It's well documented here.
It is only a client side solution. It does not have a hard requirement on any particular web server (but it is convenient if you have NodeJS installed so that you can use something like Browserify to compile and package scripts).
It's not clear from your question what parts of Sails you're planning to use. If you want to use React in an isomorphic way (meaning you'd run React code on the web server and it would be then "attached" by the React client code, without re-rendering), then data management could be an issue if you're using Waterline. But, if you're only going to use React on the client, then it may be an easier integration.
But, again, it's not necessary to use Flux. You can just follow the basic principles of using React JS regarding data flow (parent to child) and use other data storage and synchronization libraries. React is not opinionated that way.
Also, while Facebook has a Flux implementation here, you'll find dozens of implementations of the pattern with various tweaks and enhancements located here. You'll also note on that same page that there are lots of other complimentary libraries that may be useful.

Architecture of a single-page JavaScript web application?

How should a complex single-page JS web application be structured on the client-side? Specifically I'm curious about how to cleanly structure the application in terms of its model objects, UI components, any controllers, and objects handling server persistence.
MVC seemed like a fit at first. But with UI components nested at various depths (each with their own way of acting on/reacting to model data, and each generating events which they themselves may or may not handle directly), it doesn't seem like MVC can be cleanly applied. (But please correct me if that's not the case.)
--
(This question resulted in two suggestions of using ajax, which is obviously needed for anything other than the most trivial one-page app.)
MVC architecture of PureMVC/JS is the most elegant IMO. I learned a lot from it. I also found Scalable JavaScript Application Architecture by Nicholas Zakas helpful in researching client side architecture options.
Two other tips
I've found view, focus, and input management are areas that need special attention in single page web apps
I also found it helpful to abstract away the JS library, leaving door open to change mind on what you use, or mix & match should the need arise.
Nicholas Zakas's presentation as shared by Dean is a very good place to start with. I was also struggling to answer the same question for a while. After doing couple of large scale Javascript products, thought of sharing the learnings as a reference architecture in case someone needs it. Have a look at:
http://boilerplatejs.org/
It addresses common Javascript development concerns such as:
Solution structuring
Creating complex module hierarchy
Self contained UI components
Event based inter module communication
Routing, History, Bookmarking
Unit Testing
Localization
Document Generation
etc.
The way I build apps:
ExtJS framework, single page app, every component defined in a separate JS file, loaded on-demand
Every component contacts its own dedicated web service (sometimes more than one), fetching data into ExtJS stores or special-purpose data structures
The rendering uses standard ExtJS components, so I can bind stores to grids, load forms from records, ...
Just choose a javascript framework, and follow its best practices. My favorites are ExtJS and GWT, but YMMV.
Do NOT roll your own solution for this. The effort required to duplicate what modern javascript frameworks do is too big. It is always faster to adapt something existing than to build it all from scratch.
Question - What makes an application complex ?
Answer - The use of word 'complex' in the question itself. Hence, a common tendency will be to look out for a complex solution right from the beginning.
Question - What does the word complex means ?
Answer - Anything that is unknown or partially understood. Example : The theory of Gravity even today is COMPLEX to me but not to Sir Isaac Newton who discovered it in 1655.
Question - What tools can I use to deal with complexity ?
Answer - Understanding and simplicity.
Question - But I understand my application . Its still complex ?
Answer - Think twice, because understanding and complexity does not co-exist. If you understand a huge huge application, I am sure you will agree that it is nothing but an integration of small and simple units.
Question - Why all of the above philosophical discussion for a question on
Single Page Application (SAP)?
Answer - Because,
-> SPA is not some kind of core technology that is newly invented for which we need to reinvent the wheel for a lot of things that we are doing in application development.
-> Its a concept driven by the need for better performance, availability, scalability and maintainability of web applications.
-> Its a fairly newly identified design pattern, so an understanding of SPA as a design pattern goes long way in making informed decisions about the architecture of a SPA.
-> At the root level no SPA is complex, because after understanding the needs of an application and the SPA pattern, you will realize that you are still creating an application, pretty much the same way you did before with some modifications and re-arrangements in the development approach.
Question - What about the use of Frameworks ?
Answer - Frameworks are boiler plate code / solution for some commonly identified and generic patterns, hence they can take off x% (variable, based on the application) load from application development but then not a lot should be expected out of them specially for heavy and growing applications. Its always a good case to be in complete control of your application structure and flow but most importantly the code for it. There should be no grey or black areas in the application code.
Question - Can you suggest one of the many approaches to SPA architecture ?
Answer - Think of your own framework based on the nature of your application. Categorize application components. Look for an existing framework that is close to your derived framework, if you find it then use it, if you do not find it then I suggest going ahead with your own. Creating framework is quite an effort upfront but produces better results in long run. Some basic components in my SPA framework will be:
Data Source : Models / Collections of Models
Mark Up for presenting data : Templates
Interaction with the application : Events
State capturing and navigation : Routing
Utilities , widgets and plug-ins : libraries
Let me know if this helped in any way and good luck with your SPA architecture !!
The best thing to do is to look at example uses of other frameworks:
TodoMVC showcases many many SPA frameworks.
You can use javascript MVC framework http://javascriptmvc.com/
The web application that I am currently working on uses JQuery and I would not recommend it for any large single page web application. Most frameworks i.e. Dojo, yahoo, google and others use namespaces in their libraries but JQuery does not and this is a significant drawback.
If your web site is intended to be small then JQuery would be ok but if you intended to build a large site then I would recommend looking at all the Javascript frameworks available and deciding which one most meets your needs.
And I would recommend applying the MVC pattern to your javascript/html and probably most of your object model for the javascript could be done as the json that you actually return from the server through ajax and the javascirpt uses the json to render html.
I would recommend reading the book Ajax in action as it covers most of the stuff you will need to know.
I'm using Samm.js in several one page applications with great success
I would go with jQuery MVC
Check out http://bennadel.com/projects/cormvc-jquery-framework.htm Ben is pretty sharp and if you dig around on his blog he has some nice posts about how CorMVC is put together and why.
Alternative: take a look to ItsNat
Think in JavaScript but code the same in Java in server with the same DOM APIs, in server is way easier to manage your application without custom client/bridges because UI and data are together.
Or have a look at https://github.com/flosse/scaleApp
NikaFramework allows you to create single-page application. Also allows you to write HTML, CSS (SASS), JavaScript into separate files and bundle them into only one output file in the end.
I would recommend to explore Yeoman. It allow you to use existing "best practice" for your new project.
For example:
if you decide to use Angular.js, there is a Yeoman generator, that give you a structure for routing, views, services, etc. Also allow you to Test, minify your code, etc.
If you decide to use Backbone, checkout this generator

Categories