Pattern for global object in React Native - javascript

Is there a well-established pattern for allowing a single object to be available to all modules in a React Native application? I know I can pass the object from the RouteMapper to every particular scene and access it that way, but that feels like a lot of boilerplate and repeated code when I am absolutely certain that I need it accessible from the entire application. In fact, I need it listening for events at all times.

Well, there is the React Context.
https://facebook.github.io/react/docs/context.html
But the general wisdom is: don't use it.

Related

Is it possible to store instances of custom class in Vuex/(Vue data)?

According to vue documentation, it is not possible to store anything besides plain objects. (https://ru.vuejs.org/v2/api/#data). I always use vuex as a DI container, I see it from this point of view. It keeps vue away from my application business logic, and makes possible describe business rules only using JS with no dependencies. But that approach breaks vue dev tool, and for some reason not all tests pass.
Is there a way to circumvent this restriction? For example class instances can be created in getters rather than in mutations. But it does not work for me because some constructors of my classes have side effects (It's not a best practice, but that what i have).
You can absolutely store class instances in the store state.
I generally store arrays of models, which is really useful to keep logic in one place.
Something like:
Api.load('/api/users').then(res => commit('users', res.data.map(User.create)))

Differences between require() and passing an object via prop or context

What's the difference between require()ing a singleton, and passing it down via React prop or context?
What are the use cases for each?
If you require() (or import) a module, you get the same object in any component.
Use modules for the code your component depends on:
Other components (Button).
Utility functions (getTextColor).
Global data storage (CommentStore).
The upside of importing a module is that it’s extremely easy to do, and you only need to do it once.
The downside of importing a module is that you can’t override what it points to. So, for example, you can’t easily swap out CommentStore or getTextColor modules in testing, or in a “living design guide”. Depending on your use case, this may or may not be a problem.
Passing something as a prop means you can pass a different thing every time.
Use props for inputs to your components that need to be customizable:
Data (comment).
Event callbacks (onClick).
UI properties (color).
The upside of using props is that they’re explicit and customizable. They’re primary mechanism of passing data down in React so when in doubt, use props.
The downside of using props is that sometimes you might end up passing a lot of props through intermediate components that don’t use them, just to get props down to the leafs. Normally this is fine in React because it trades some verbosity for ease of finding bugs. But in some cases it can get frustrating.
Context is an advanced API and should be used very sparingly.
It is likely that it will significantly change in the future.
Context is like implicitly passed props that become “global” for a subtree:
Theming (currentTheme).
Locale (currentLanguage).
Dependency injection (store).
The advantage over props is that you don’t need to pass them manually through every component. The advantage over importing is that you can override it from outside the component, which is handy for testing, server rendering, and for things that change.
The downside of context is that it has severe issues with updates, so don’t rely on its value updating correctly. For example, React Redux can safely pass store down because store itself never changes and has its own subscription mechanism.
In general we don’t suggest using context in your application code directly. It’s fine if some libraries use it because they will be easier to migrate when its API changes.
Finally, I’m not a natural painter, but here’s a doodle to sum it up:

Custom events versus callbacks in ReactJS

I'm new to ReactJS and I'm trying to figure out how to store and manipulate global state. For example, I'm writing an editor app that has some global state: selected color/background, active tool, current selection, etc.
I'm thinking about having a root interface component to store this information, and I'm ok with explicitly passing the state around using properties. I guess the idiomatic way for a children component to change global state is calling a callback received from the parent - personally I find this a bit annoying.
Instead, I'm firing custom events at the children and setting listeners on the parent. So far it is working really well, but I looked at a lot of sample code and never saw people using this pattern.
Is there any practical consequences I should consider?
Flux is great for manipulating global state because the Stores are globally accessible. Globals are known to be bad, but the way you interact with the Stores is through Actions. Actions make the state predictable and localized. So even though the state storage itself is global, Actions make the state interactions very local. At work we tend to do both reading & writing through Actions, so every state change is an "event" that leads to easily programmable behavior.
I really wouldn't compare Flux to Angular as their principles and flows are entirely different. Suggest you try Reflux.

Where would you instantiate nested components using Closure Library?

Closure library offers a basic life cycle for Components:
Instantiation
Rendering/Decoration
Document Entering
Document Exiting
Disposal
I'm focusing on the first two. About design patterns, when is it better to instantiate a nested component in the first steps?
Instantiation: needs to be hold on a property till added through addChild and consumes memory before necessary. Anyways, it allows to do some dependency injection or better initialization because of the parameters it receives.
Rendering/Decorating: messes up the dom creation, which can be already complicated because of the references of other objects it needs. It also would need the instantiation parameters previously stored in some property. Anyways, holds the instantiation till is needed.
Maybe a separated method called after instantiation which wraps the rendering? I'm asking because Closure Libray book and documentation don't talk about this.
Doing some refactorying and trying to split logic, came to the following conclusion:
The best option I've found so far is to create the components inside the createDom method:
Normally, the parameters needed for components involve the data they present. My arquitecture uses DAO, which means all data objects are conveniently connected. Subcomponents usually need some other data objects which are accessible by the parent's DAO. Since the parent object is needing this DAO, it's ok to store it on a property for the use inside the createDom.
The other thing is that instantiation and rendering in the createDom component, theoretically, only needs two lines, which isn't a mess.
Again, it's the best possible solution to increase cohesion.

Dependency Injection vs. Managed Dependencies vs. Global Object

I'm working within a Javascript + BackboneJS (an MVC framework) + RequireJS framework, but this question is somewhat OO generic.
Let me start by explaining that in Backbone, your Views are a mix of traditional Views and Controllers, and your HTML Templates are the traditional MVC Views
Been racking my head about this for a while and I'm not sure what the right/pragmatic approach should be.
I have a User object that contains user preferences (like unit system, language selection, anything else) that a lot of code depends on.
Some of my Views do most of the work without the use of templates (by using 3rd party libs, like Mapping and Graphing libs), and as such they have a dependency on the User object to take care of unit conversion, for example. I'm currently using RequireJS to manage that dependency without breaking encapsulation too much.
Some of my Views do very little work themselves, and only pass on Model data to my templating engine / templates, which do the work and DO have a dependency on the User object, again, for things like units conversion. The only way to pass this dependency into the template is by injecting it into the Model, and passing the model into the template engine.
My question is, how to best handle such a widely needed dependency?
- Create an App-wide reference/global object that is accessible everywhere? (YUK)
- Use RequireJS managed dependencies, even though it's generally only recommended to use managed dependency loading for class/object definitions rather than concrete objects.
- Or, only ever use dependency injection, and manually pass that dependency into everything that needs it?
From a purely technical point of view, I would argue that commutable globals (globals that may change), especially in javascript, are dangerous and wrong. Especially since javascript is full of parts of code that get executed asynchronously. Consider the following code:
window.loggedinuser = Users.get("Paul");
addSomeStuffToLoggedinUser();
window.loggedinuser = Users.get("Sam");
doSomeOtherStuffToLoggedinUser();
Now if addSomeStuffToLoggedinUser() executes asynchronously somewhere (e.g. it does an ajax call, and then another ajax call when the first one finishes), it may very well be adding stuff to the new loggedinuser ("Sam"), by the time it gets to the second ajax call. Clearly not what you want.
Having said that, I'm even less of a supporter of having some user object that we hand around all the time from function to function, ad infinitum.
Personally, having to choose between these two evils, I would choose a global scope for things that "very rarely change" --- unless perhaps I was building a nuclear powerstation or something. So, I tend to make the logged in user available globally in my app, taking the risk that if somehow for some reason some call runs very late, and I have a situation where one user logs out and directly the other one logs in, something strange may happen. (then again, if a meteor crashes into the datacenter that hosts my app, something strange may happen as well... I'm not protecting against that either). Actually a possible solution would be to reload the whole app as soon as someone logs out.
So, I guess it all depends on your app. One thing that makes it better (and makes you feel like you're still getting some OO karma points) is to hide your data in some namespaced singleton:
var myuser = MyApp.domain.LoggedinDomain.getLoggedinUser();
doSomethingCoolWith(myuser);
in stead of
doSomethingCoolWith(window.loggedinuser);
although it's pretty much the same thing in the end...
I think you already answered your own question, you just want someone else to say it for you : ) Use DI, but you aren't really "manually" passing that dependency into everything since you need to reference it to use it anyways.
Considering the TDD approach, how would you test this? DI is best for a new project, but JS gives you flexible options to deal with concrete global dependencies when testing, ie: context construction. Going way back, Yahoo laid out a module pattern where all modules were loosely coupled and not dependent on each other, but that it was ok to have global context. That global context can make your app construction more pragmatic for things that are constantly reused. Its just that you need to apply that judiciously/sparingly and there need be very strong cases for those things being dynamic.

Categories