Multiple render variants with React? - javascript

I've built a web application using React which is up and running and working well. I should probably just leave it alone, but there's one area which is troubling me, where I think I need to do a bit of refactoring because what I'm doing doesn't seem to me to be going with the flow of React. I'd be interested in others' views.
I have a React class, Product, which I use to keep track of products on the page. The only property stored in state is 'quantity', but I have various functions which do things like update a basket by means of pub/sub. Depending on how and where this Product class is used (whether in a table or for a detail view, whether on mobile or desktop), the necessary display is quite different. So in my render function, I call variously 'renderForDetailOnMobile', 'renderForTableOnMobile', 'renderForDetailOnDesktop' and 'renderForTableOnDesktop'.
As I say, this doesn't feel very React-y to me, as if I've got the whole thing upside down (although the rest of the app is, I would say much more idiomatic). So how should be thinking this through in order to break it down into separate smaller classes, which is what I imagine I should be doing? Sorry, for privacy reasons it's not possible to poast actual code, so I hope this description makes the situation clear enough.

You should be using reducers or stores, depending whether you have a flux or redux application. This would help you to understand your state and how it changes.
I see you are using state in your Product, while you should be using stores as mentioned above.
So, how I see the issue is that you have data source and you need to transform it based on the device requirements.
In such case I would make a container which would load other components in charge of transforming and presenting data for different devices.
Container should be rather simple just returning the correct component based on the conditional being met.

Related

Using mutationobservers to detect changes in the results of a fetch request

I'm working on a narrow cast that displays an amount of tickets (an integer with the total added up to eachother) from a 3rd party API. I want to display a notification when this amount increases. I've read about mutationobservers, and that they are good for doing similar tasks like when something gets added or deleted.
The app has a Vue frontend, and a Laravel backend which does the requesting/authenticating. The index blade loads in a Vue component which contains the other components (and distributes the data from the API to child components).
I'm not quite sure wether mutationobservers are good for this specific job, though. Googling really didn't give me great alternatives.
In conclusion, I want to know if mutationobservers are the right tools for this task and what property would work. Better suited alternatives are also welcome.
Using vue, you can use a watcher function to watch for changes in a particular variable (amount). Mutation Observers only watches for dom updates, it won't give you what you want

Angular JS cascade notifications

I need your advice to help me.
I'm making an Angular JS app and I need some notifications like angular-toastr or angular-ui-notification but showing not like a list but cascade. Like in picture bellow.
Can anybody help with advice or realization such kind of notifications?
So I think what you want to do is divide and conquer this problem:
Think about the UI as a set of components. For the picture above, you might have the following.
// Notification Cascacder applies DOM transformations to a list of
<notification-cascader>
// Iterates over a list of notifications
<notification-list>
// Contains primary DOM for a notification
// accepts a variety of arguments for opacity, notification-message, etc.
<notification-card> </notification-card>
</notification-list>
</notification-cascader>
Now that you've broken it up you can determine what the API for each component may be, write the tests and then code the component. Writing it in this way will increase the reusability of each of the angular components. You could use a single notification-card without its parent in parts of the application. Although it isn't angularjs related you can read this and apply the concepts
https://reactjs.org/docs/thinking-in-react.html

ReactJS local vs global state and implementing redux at a later time

So we are about two months in on a project. This is the first time I have ever managed code writers and not written the code myself. I've been reading their code for the last week. What was suppose to be a simple React app has turned into a spaghetti mess.
I understand: redux helps to manage global state. But should that mean that all buttons should map to a global "action?" This has seemed to create this entire mess of objects scattered throughout the entire app. I keep asking myself, why are we using global state for everything when local state could be used for 90% of the application. This is the kind of code that gives me heartburn:
let subitems = SidebarItems[state.type].sub_items;
Store.dispatch(SidebarSubItemHandler(item.action, subitems[0], null));
if(item.sub_items[subitems[0]].param) {
browserHistory.push(`${item.sub_items[subitems[0]].path}/${item.sub_items[subitems[0]].param}`);
} else {
browserHistory.push(item.sub_items[subitems[0]].path);
}
subItembuttons = Object.keys(this.props.subitems.sub_items).map(subitem => {
let subItem = this.props.subitems.sub_items[subitem];
return <li className={this.props.activeSubItem.action == subItem.action ? "bottom-bar-item active" : "bottom-bar-item"}
onClick={e => this.props.onClickSubItem(e, subItem)}
key={subItem.action} style={this.props.subitems.inlineStyles.mobileSubItemLI}>
{subItem.item}
</li>;
});
The application is littered with all kinds of objects like these that map to "action" objects. So at this point we are making the decision to scrap the entire project and restart from scratch, but without redux. Let's try to do as much as possible using local state only. When it comes time, and we need global state for something, ONLY implement it for that something, not every single action in the app. Does this make sense?
So I guess my question is: If we develop an app using local state and just fundamental React, will we be creating un-reversable problems that would prevent us from implementing redux on a per item basis?
Quoting from the relevant Redux FAQ entry at http://redux.js.org/docs/faq/OrganizingState.html#organizing-state-only-redux-state:
Using local component state is fine. As a developer, it is your job to determine what kinds of state make up your application, and where each piece of state should live. Find a balance that works for you, and go with it.
Some common rules of thumb for determing what kind of data should be put into Redux:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
Per your specific question: if you use the "container component" pattern fairly consistently, it should be relatively straightforward to swap those "plain React" containers for Redux-connected containers down the line. See https://github.com/markerikson/react-redux-links/blob/master/react-component-patterns.md#component-categories for articles on the "container/presentational component" pattern.
Two other thoughts. First, I recently co-authored an article that discusses why you might want to use Redux in a React application.
Second: yeah, that code looks kinda ugly. I'm hoping those are at least three different snippets from different parts of the codebase, rather than one snippet, but that's rather hard to read. The repeated use of "sub_items" and "subitems" seems like a bit of a red flag, readability-wise.
It also doesn't look like it's following good Redux practices. For example, idiomatic Redux code almost never references the store directly. Instead, references to dispatch and getState are available via middleware, and thus can be used in action creators via redux-thunk and redux-saga. Connected components can also access dispatch.
Overall: you are absolutely welcome to use as much or as little Redux as you want, and as much or as little local component state as you want. I think the larger issue, though, is how well your team actually understands Redux, and how they're trying to use it.

How to deal with component state with redux?

I have been using vanilla React for a while, and have now decided to take a closer look at Redux for a new project I am doing.
At first I got the impression that all user activity should result in actions, with one of the main reasons being that you would be able to reconstruct any application state by just playing back the appropriate actions.
The problem with this, however, is that you put a lot of stuff in the store that in reality does not feel like application state. Stuff like "If I focus on this input, the label turns green" does not seem like state fitted for being represented in the application state of an application that is potentially composed by hundreds of components. These things make total sense with the typical todo-tutorial, but it can be difficult to see how it will turn out in a more complex scenario.
Then I read some more, and found that the general opinion, backed by creator Dan Abramov, is that you should usually combine local component state with the application state (store). "Whatever seems least awkward" seemed to be the rule of thumb for where to store state.
On one hand this makes total sense: The things that are really application state, and are relevant for multiple components should be in the store, while the strictly presentational details that only concerns one single component should be handled using normal react state. On the other hand this approach confuses me a bit, because of what I wrote in the beginning: Isn't a big part of the point with redux that you avoid having the state distributed among the components, and that you are able to recreate state by just storing the actions?
I hope someone can shed some light on this concern, because it has been bothering me, and it is something I think I should get a solid opinion about before trying to build something complex with redux.
What state you put where is entirely up to you. Sometimes it may make sense to put everything in Redux, sometimes it may make sense to keep stuff in a component. I recently saw some good rules-of-thumb:
Do other parts of the application care about that data?
Do you need to be able to derive further data from that data?
Is the same data being used to drive multiple components/features?
Is there value to you, to being able to restore the state to a given point in time (ie: time travel / debugging)?
Do you want to cache the data, ie: reload it from state if it's already there instead of requesting it again?
(Credit to https://www.reddit.com/r/reactjs/comments/4w04to/when_using_redux_should_all_asynchronous_actions/d63u4o8 for that list.)
Also see the Redux FAQ on this topic: http://redux.js.org/docs/FAQ.html#organizing-state-only-redux-state .

How to refactor to cleaner version of maintaing states of the widget

Backstory
I inherited a bunch of code that I'd like to refactor. It is a UI application written in javascript.
Current state:
We have main application which consist of several UI components. And each component has entry fields, textboxes, menus, etc), like "ticket", "customer information", etc. Based on input, where the application was called from, who is the user, we enable/disable, hide, show, change titles.
Unfortunately, the app grew to the point where it is really hard to scale, add new features. Main the driver (application code) calls set/unset functions of the respective components. So a lot of the stuff look like this
Main app unit
function1() {
**call_function2()**
component1.setX(true);
component1.setY(true);
component2.setX(false);
}
call_function2() {
// it may repeat some of the code function1 called
}
and we have a lot of this in the main union.
I am cleaning this mess. What is the best way to maintain the state of widgets?
Please let me know if you need me to clarify.
Looking at your code looks like you are accessing your view code directly from functions which as you correctly pointed is a bad idea. If you application is lot of GUI stuff then I would suggest you go with MVVM approach.
It would keep your view, binding and functionality completely separately. In future if you want to change the GUI, you can do it without touching any other classes.
Well I am not from JS background, but this is what my .Net exp says.

Categories

Resources