How to make React Service as Singleton, Injectable, and Redux Connected - reactjs

Summary
I am writing a React-Redux application, and would like to create a service that can be accessed across multiple components, with the following characteristics:
Singleton (just gets instantiated once across the entire
application)
Injectable (can be injected into, and used by, multiple components across the application)
Redux Connected (can access the entire Redux state tree & received updates to state changes)
Code Example
The type of solution I have in mind, would allow me to inject a service int a React Component, and use in the following way:
{ featureAvailabilityService.isAvailable('myFeature') && (<MyFeature />) }
Ideas
I have read about High Order Components, Hooks, and the Context API. There are also some interesting libraries, such as Unstated, and Redux-Logic. I feel like the best answer probably lies somewhere between these, but could use some guidance to put me on the right track.
Use Case
In this instance, I would like to create a reusable service, which has methods to determine the availability of certain features. This involves relatively complex logic based on System, Tenant, and User configuration and state. It also requires the service to have access to state from several different parts of the application. It will also be reused broadly across the application.
Why Yet Another React Service Question?
I realize there are already a lot of similar questions to this, usually from people with an Angular background, looking for the React equivalent to an Angular Service. However, I have not yet found an answer that provides for the above three criteria... or at least not one that I understood.
Thanks for any input.

Related

Managing Big Data in Angular2

I'm following an Angular2 course having a background of Sencha ExtJS framework.
My question is pretty easy : with AngularJS how do you store and interact with big data structures? In all the course when a Service was retrieving data was always small and was stored in an array.
Why did I mention ExtJS? Because it offers classes called Store to, as the name says, store data and query it, with possibility of filtering,sorting,mapping and so on.
Let's make an example :
I have the list of the airports in the world and I want to offer it in a select. Of course i will setup the service injected to the select that offers the entire list. But then:
-I want to filter it as the user go on typing
-The array containing the data is an array of objects with other properties after the name like the country or the id
Which is the approach to follow?
As per my comments, here's my answer.
In Angular 2 we have smart components, which hosts logic and data, and dumb components which are pure views, with no logic and preferably stateless.
Ideally, you could retrieve your data from the API and deliver it to your smart components either returning the whole data or exposing a stream with RxJS.
An example using RxJS would be:
A service calling the APIs and returning an Observable with the data
A smart component consuming the service's data, in the form of a Subscription
One or more dumb component in showing the data which is pushed down by the smart component (acting as a container)
At this point, your data manipulation could reside either in the service or in the smart component (it depends on what you need to transform and how).
To manipulate the data, I suggest you use RxJS which offers the possibility to chain streams and filter, aggregate, map, ... methods. It is asynchronous.
If you can go for something less complex but blocking (it depends on your requirements), I'd suggest you use Lodash, which brings methods for collections to chain, map, filter, and aggregate data.

React and UI updates on data changes (via backend)

Learning a little React currently. I'm finding myself confused about some of the utility here. One sticking point that seems to (for me, at least) undermine it's value is that If I want to sync my UI to data residing on the server (which can and will change), I need to manually poll the server? Aside from component-based architecture, I'm not sure how this is getting me further than well structured and logically implemented AJAX. Even in the React docs, they're using JQuery in this regard. https://facebook.github.io/react/docs/tutorial.html#updating-state
I'm sure I'm missing the forest for the trees or whatever.
Thanks!
React is (citing their page)
a javascript library for building user interfaces
The main focus is to build a view layer for your application. This means you have full freedom in choosing what to use to fetch your data. For simple uses it can be jQuery or fetch.
It's generally recommended to not fetch data directly in your components and use one of Flux pattern implementations, e.g. Redux.
If your application has to be constantly powered by new data from server you can think about using something like RethinkDB on your backend and connect it to Flux store on your frontend.

Angular 2 - Including a provider in a service

I have a service loaded into a component as a provider. This service may return data using Http or it may not, the component should not care. However, it seems that the component itself must include HTTP_PROVIDERS if the loaded service uses Http. This breaks separation of concerns. What am I misunderstanding?
This breaks separation of concerns. What am I misunderstanding?
In order to support instantiating multiple instances of a service (i.e., so all services don't have to be singletons), an Angular app needs a way to specify multiple injectors (not just one). These injectors need to be created and configured in some kind of hierarchy. The component/directive tree, since it is a tree, already has a hierarchy. So Angular uses the (existing) component tree to configure dependency injection. I like to think of it as a sparser "injector tree" that overlays the component tree.
I think it would be more work to define a separate hierarchy for services – we, as developers, would probably have to define and configure another injector tree of some sort.
So instead of thinking of it as "components need to know the dependencies of services" (which, when stated that way, it does sound like we're breaking separation of concerns), I like to think of it more like the following: "when I write an Angular app, I have to configure my providers/dependencies on the injector tree"... and since the injector tree overlays the component tree, I use components to configure it.
But this is not ideal, since if you want to reuse components in a different app, you might need to change the providers arrays (i.e., you may need to reconfigure the injector tree).
In fact, it's better to specify the HTTP_PROVIDERS when bootstrapping your application:
bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
But I agree with you that there are some impacts on having configuration of providers only on components.
The previous configuration will work because of hierarchical injectors.
See this question for more details about hierarchical injectors:
What's the best way to inject one service into another in angular 2 (Beta)?

How to implement service(concept in AngularJS) -like component in React

All:
I am pretty new to React from AngularJS. In AngularJS, there is service dependency inject which can provide a service instance to do data fetching, processing, etc., other than UI operation. I wonder how to do this(or implement that injection) in React component?
Thanks
I prefer to create a service in another file that exposes the 'public' functions through module.exports.
e.g.
module.exports = {
foo: function(){ return bar; }
}
which is then referenced by Components using
import myService from './routetoservice/myService'
An Extension to Michael Dunn's Answer
This is the actual answer ,
Service pattern is not limited to any programming language or
library.
We can implement this concept in any language , Even we can
implement this in react
A tiny service can be created on server OR in ui browser in Javascript that serves some logical purpose
It gives us benefits of code availability, code management , code isolation of particular logic
Its a very native way for code availability, code management , code isolation of particular logic
If we compare redux/flux vs services ,redux/flux also serve these purpose's
Currently i am using redux and its actions , and also created my tiny services on ui when required.
No need to use OTHER NPM MODULES FOR CREATING SERVICES , Just Michael Dunn's solution is enough
In reactjs we use the flux pattern to provide data handling. Here is an example of that with reflux. React with Flux: is this the dogmatic pattern or are there equal/better options?.
React seems philosophically opposed to services in the Angular sense, apparently preferring tight coupling of UI and logic.
But I have found a react-services module, which seems to offer what you are after:
• separate your component and application state by introducing a service layer that takes care of propagating changes through your application
• manage component dependencies in an explicit, testable way
• there's no events and no lifecycle management - everything is done automatically for you
• it's tiny and easy to understand - the core is less than 100 lines of code
https://medium.com/#alshdavid/react-state-and-services-edb95be48851
Here's an article showing how to do it with nothing but React Context and rxjs

Changing my backbone.js router

I have a web application with require.js, backbone.js and jquery.
The brief structure of the app is as follows:
There are 2 sections on the screen (toolbar and main content below).
There are multiple components (address management, event management), each triggered by a hash fragment change and require a
page transition.
There is one backbone.js router. It's the heart of the application. The router is activated with a new hash fragment (manually entered,
back button, menu item selection).
Up until now, in the router, I made the page transition, I DIRECTLY called the controller ("view" in backbone) of the selected component.
So there's a CENTRAL handling of controller calling.
But this has to change now to a DISTRIBUTED handling. I now need to respond to a new hash fragment from two different places: From the toolbar component and from router.
So my idea is to exchange the direct controller calling mechanism with pub sub. Now MULTIPLE components could register for a special action and the router just "fires the event".
I searched around and found Chaplin (https://github.com/moviepilot/chaplin), a backbone.js example application.
The developers of Chaplin seem to have a similiar thing called "ApplicationView" (https://github.com/moviepilot/chaplin#toc-router-and-route):
"Between the router and the controllers, there’s the ApplicationView as
a dispatcher."
Is there anyone who has already this kind of architecture and can tell me his experience with this or has anybody solved this in another way?
I've used a similar, though maybe less complex, architecture in this project. I give a pretty good explanation in this answer to a related question. The quick overview:
I manage app-wide events that change the application state using a singleton State model that works similarly to Chaplin's pub/sub architecture. This is just a basic Backbone model, with some added methods to deal with serializing and deserializing attributes as strings, so they can be set in the URL.
Application components that change the application state in response to user interaction or other input do so by setting properties on app.state.
Components that need to update when the application state changes do so by binding to change events on app.state (it looks like this is exactly the way Chaplin's mediator works, though they renamed the methods to fit the pub/sub paradigm).
I treat my routers like specialized views that update the address bar and respond to user input in that area. Changing the address (manually or by clicking on a link) causes the router to set() the necessary changes on the app.state model, and everything else updates accordingly.
I hope that's helpful - I think it's a little simpler than the Chaplin approach.

Resources