Why use NGRX instead of constructor injected services? - javascript

Wondering why one would use NGRX or NGXS for an Angular app instead of constructor injected services to handle component IO?
Is it only to ensure that component properties references are never mutated without switching out the entire property value reference or is there more to it?
Altnernative to NGRX
per the answer I developed:
Slice.
I believe it does everything NgRx / NgXS does (With the exception of a time machine - but this is easy to implement via delta notifications - already supported). but with zero boilerplate.
Here's an article showcasing some of the capabilities:
https://medium.com/#ole.ersoy/storing-users-in-the-reactive-slice-object-store-5ea0fab06256

You will need to write a service that provides a consistent and easy to change api to modify the data, you will need to come up with a fast and well tested way of querying the data, you will need to write and maintain observables for all your data. You will have to write and establish a pattern for async calls. You will have to write an api to access the data in your templates.
By the time you are done you will end up with something resembling ngrx.
For a simple one service data, ngrx is overkill, lots of boilerplate, but for a reactive app with multiple data sources or complex data interactions across numerous developers having a well used library is really helpful.
Follow SO answer for more in depth explanation: What are benefits of using store (ngrx) in angular 2
To understand, when to use which approach, read this: RxJs and Ngrx Store - When to Use a Store And Why?

Related

Vuex vs Service for managing state

What is the difference (benefits/cons) of using Vuex vs a service for state management.
I am working on an application that displays a catalog of items. These items are fetched from an API. At the moment users have the ability to apply filters and sort the items.
I am using a service to handle updating the view based on what filter the user applies. The items are filtered on the back end so each time a filter is triggered an update method fetches the items from the API.
There's a few levels of component nesting for this application (and these are reused among diff pages with sim functionality) and I used an event bus as a quick way to handle the events and test the API endpoints, but now I need to use Vuex to handle the state.
I am starting to write the Vuex store and I am noticing there's quite a bit of functionality that I'm transferring over from the service.
I would like to know how the too differ?
I'm relatively new to VueJS, so please take this with a grain of salt.
I think it depends on the size of the app, as well as the complexity. If you're emitting a lot of events, using state makes sense because you have a single source of truth (a single file, literally) for your app state vs an event bus which will have to be imported into every component. From the Vuex site,
If you've never built a large-scale SPA and jump right into Vuex, it may feel verbose and daunting. That's perfectly normal - if your app is simple, you will most likely be fine without Vuex. A simple global event bus may be all you need. But if you are building a medium-to-large-scale SPA, chances are you have run into situations that make you think about how to better handle state outside of your Vue components, and Vuex will be the natural next step for you. There's a good quote from Dan Abramov, the author of Redux.
Hope this helps. Good luck :)

Creating Cycle.js reusable modules

Let's imagine, in a OO world, I want to build a Torrent object which listens to the network and lets me interact with it. It would inherit an EventEmitter and would look something like this:
var torrent = new Torrent(opts)
torrent.on('ready', cb) // add torrent to the UI
torrent.on('metadata', cb) // update data in the UI
and I can also make it do things:
torrent.stop()
torrent.resume()
Then of course if I want to do delete the torrent from memory I can call torrent.destroy().
The cool thing about this OO approach is that I can easily package this functionality in its own npm module, test the hell out of, and give users a nice clean reusable API.
My question is, how do I achieve this with Cycle.js apps?
If I create a driver it's unclear how I would go about creating many torrents and having their own independent listeners. Also consider I'd like to package functionality in a way that others get to easily reuse it in other Cycle.js apps.
It seems to me that you are trying to solve a problem thinking about it as you would write "imperative code".
I think creating Torrent instances with their own listeners is not something you should be using in cycle components.
I would go about it differently - creating Torrent module and figuring out what would be its sources and sinks. If this module should be reusable and published, you can create it as a function that would receive streams as arguments. Maybe something similar to TodoMVC Task component (which is then used in its parent component).
Since this module can be created as a pure function, testing it should be at least just as easy.
This implementation of course depends on your requirements but communication with the module would then be done only with streams and since it would be declarative there would be no need for methods like stop() and destroyed() which you would call from elsewhere.
How do I test it?
In cycle.js you'd write a component with intent model and view functions.
You'd test intent(), for given input Streams, produces Streams of actions that you want. For models, you'd test that given http and action streams, you get the state you want, and for view, you test that given a state you get the VDom you want.
One tricky bit with cycle.js is that since it passes functions around, normal JavaScript objects that use the 'this' keyword are not worth the trouble due to 'this' context problems. If you are working with cycle.js and you think you might write a JS class for use with Isolate, Onionify, or Collections most likely, you are going in the wrong direction. See MDN docs about 'this'
how I would go about creating many torrents
The Cycle.js people have several ways to deal with groups of things like this.
This ticket describes some things that might work for that:
Wrap subapp in Web Component
Stanga and similars.
Cycle Collections
Cycle Onionify

Redux & RxJS, any similarities? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I know Redux is a better "implementation" of Flux, or better saying it's a redesign to simplify things (application state management).
I have heard a lot about reactive programming (RxJS), but I haven't dived to learn it yet.
So my question is: are there any intersection (anything in common) between this two technologies or they are complementary? ...or totally different?
In short, they are very different libraries for very different purposes, but yes there are some vague similarities.
Redux is a tool for managing state throughout the application. It is usually used as an architecture for UIs. Think of it as an alternative to (half of) Angular.
RxJS is a reactive programming library. It is usually used as a tool to accomplish asynchronous tasks in JavaScript. Think of it as an alternative to Promises.
Reactive programming is a paradigm (way of working and thinking) where data changes are observed from a distance. Data is not changed from a distance.
Here is an example of changed from a distance:
// In the controller.js file
model.set('name', 'George');
The Model is changed from the Controller.
Here is an example of observed from a distance:
// logger.js
store.subscribe(function (data) {
console.log(data);
});
In the Logger, we observe the data changes that happen in Store (from a distance), and write to the console.
Redux uses the Reactive paradigm just a little bit: the Store is reactive. You do not set its content from a distance. That's why there is no store.set() in Redux. The Store observes actions from a distance, and changes itself. And the Store allows others to observe its data from a distance.
RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic building blocks, Observables, to accomplish this "observing from a distance" pattern.
To conclude, very different things for different purposes, but share some ideas.
They are very different things.
RxJS can be used to do Reactive Programming and is a very thorough library with 250+ operators.
And Redux is as described on the github repo "Redux is a predictable state container for JavaScript apps".
Redux is just a tool to handle state in apps. But in comparison you could build a full app in just RxJS.
Hope this helps :)
Redux is a just a state management library coming with well defined standards for update operations. As far as you stick with the standards you can keep your data flow sane and easy to reason. It also brings the ability to enhance the data flow with middlewares and store enhancers.
RxJS is a toolkit for reactive programming. You can actually think of every thing happening in your app as a stream. RxJS gives a very rich tool set to manage those streams.
Where RxJS and Redux intercepts? In redux you update your state with actions and obviously these actions can be treated as streams. Using a middleware like redux-observable (you don't have to) you can implement your so called "business logic" in a reactive way. Another thing is that you can create an observable from your redux store which sometimes might be easier than using an enhancer.
To put it in short:
Redux: Flux inspired Library used for State Management.
RxJS: It is another Javascript library based on the reactive programming philosophy, used to deal with "Streams" (Observables, etc.) [Read about Reactive Programming to understand the Stream concepts].
I just wanted to add some pragmatic differences from when I did Redux-inspired RxJS-code.
I mapped each action type to a Subject instance.
Each stateful component will have a Subject that is then mapped into a reducer function.
All reducer streams are combined with merge and then scan outputs the state.
The default value is set with startWith just before the scan. I used publishReplay(1) for states, but might remove it later on.
The react pure render function will be to only place where you produce event data by sending in all the producers/Subjects.
If you have child components, you need to describe how those states are combined into yours. combineLatest might be a good starting point for that.
Notable differences in implementation:
No middleware, just rxjs operators. I think this is the biggest power and weakness. You can still borrow concepts, but I find it hard to get help from sister communities like redux and cycle.js since it's yet another custom solution. That's why I need to write "I" instead of "we" in this text.
No switch/case or strings for action types. You have a more dynamic way of separating actions.
rxjs can be used as a tool elsewhere, and is not contained to state management.
Less number of producers than action types(?). I'm not sure about this, but you can have many reactions in parent components that listen to child components. That means less imperative code, and less complexity.
You own the solution. No framework needed. Good and bad. You will end up writing your own framework anyhow.
It's much more fractal, and you can easily subscribe to changes from a sub-tree, or multiple parts of the app state tree.
Guess how easy it is to do epics as redux-obseravble do? Really easy.
I'm also working on much bigger benefits where the child components are described as streams. This means that we don't have to complect parent and child state in the reducers, since we can just ("just") recursively combine the states based on the component structure.
I also think about skipping react and go with snabbdom or something else until React handles reactive states better. Why should we build our state upwards just to break it down via props again? So I will try to make a version 2 of this pattern with Snabbdom.
Here's a more advanced but small snippet where the state.ts file builds the state stream. This is the ajax-form component's state which gets an object of fields (inputs) with validation rules and css styles. In this file we just use the field names (object keys) to combine all the children's states into the form state.
export default function create({
Observable,
ajaxInputs
}) {
const fieldStreams = Object.keys(ajaxInputs)
.map(function onMap(fieldName) {
return ajaxInputs[fieldName].state.stream
.map(function onMap(stateData) {
return {stateData, fieldName}
})
})
const stateStream = Observable.combineLatest(...fieldStreams)
.map(function onMap(fieldStreamDataArray) {
return fieldStreamDataArray.reduce(function onReduce(acc, fieldStreamData) {
acc[fieldStreamData.fieldName] = fieldStreamData.stateData
return acc
}, {})
})
return {
stream: stateStream
}
}
While the code might not say much in isolation, it shows how you can build state upwards, and how you can produce dynamic events with ease. The price to pay is that you need to understand a different style of code. And I love to pay that price.

Impact of using immutable.js with angularjs

There is a very powerful library called immutablejs
The philosophy comes from functional programming that a data structure is immutable and that every operation on a data structure creates a new one. This makes the program more modular, easy to prove and easier to multiprocess the data.
Currently it is used in reactjs. I like the concept from using the scala language. Would it be a good idea to use it with angularjs or would it make a mess with the watcher of the objects, as they would think that all objects were created from scratch and change the whole dom connected to this model on a certain digest?
There is a angular-immutable module availble for the use which has a directive to optimize the digest cycle of the angular when used with immutableJS. You can learn more about it from the author's blog post
Angular 2 will be able to use immutable objects in order to speed up change detection.
Take a look at: http://victorsavkin.com/post/110170125256/change-detection-in-angular-2

Flux architecture misunderstanding in example chat app

I'm trying to understand the Flux example chat app. The authors mention this unidirectional data flow:
However, in the example app there are dependencies between Action Creators (ChatMesssageActionCreator) and Stores (MessageStore), and between Stores (MessageStore, ThreadStore) and Web API Utils (ChatMessageUtils), which seems to be against the unidirectional data flow rule:
Is it recommended to follow the given example, or should one design a better pattern?
Update
I figured out that the ChatMessageUtils doesn't belong to Web API Utils, so the two arrows from store shouldn't point there, therefore maybe they're okay.
However the connection between the ActionCreators and the Store seems still strange.
The example is a bit forced, and it was created with the purpose of trying to show how waitFor() works. The WebAPI aspect of the example is pretty half-baked and really should be revised.
However, even though MessageStore.getCreatedMessageData(text) passes a value to the store, it's still a getter. It's not setting data on the store. It's really being used as a utility method, and a good revision (pull request?) would be to move that method to a Utils module.
To improve upon the example for the real world, you might do a couple things:
Call the WebAPIUtils from the store, instead of from the ActionCreators. This is fine as long as the response calls another ActionCreator, and is not handled by setting new data directly on the store. The important thing is for new data to originate with an action. It matters more how data enters the system than how data exits the system.
Alternatively, you might want to have separate client-side vs. server-side IDs for the messages. There might be few advantages of this, like managing optimistic renderings. In that case, you might want to generate a client-side id in a Utils module, and pass that id along with the text to both the dispatched action and the WebAPIUtils.
All that said, yes the example needs revision.

Categories

Resources