Redux model methods - reactjs

What if I have very common situation like.
users:[
{
firstName:'Jack',
lastName:'Daniels'
}
]
I want to have getFullName, method, what is a proper way to do that in Redux, we all know that it's possible to make it markup. I have very complicated data structures and it's not that easy to make it in markup

In JavaScript, there is no need to couple the data and the methods that act on that data. Redux stores an immutable state object without methods. You just need to find somewhere else to put those methods. In this case, I would create a utils/people.js that exposes all the methods that are required to work on people. You can then pass the state from redux to that method and get everything you need.
Assuming your state in Redux looks something like:
{ firstName: 'John', lastName: 'Smith' }
You can have utils/people.js:
exports getFullName(state) {
return `#{state.firstName} #{state.lastName}`;
}

Related

want to know the disadvantages of using state (this.state) react components (not redux)

i just want to know this.whether state json object binding and normal json object binding is same or not? below is the example.
1st example
state = { name: "Default", email: "" };
binding data : this.state.name
this.setState({ name: e.currentTarget.value })
2nd example
const data= {name: "Default", email: ""}
binding data to control: data.name
onchange={e=>data.name=e.value}
both are working fine but want to know which one is better in performance?
my application dosent need any imutable data because i not displaying data dynamically i need to fetch the data from api on component load and posting the data to api on form submit. so i am using the 2nd approch. where i feel state will unnecessarly load render object.
so can any one suggest which one is better?
If the state is not associated with any UI component then changing it will not re-render anything so functionally both will work the same.
In terms of performance 2nd approach will be faster as it is a direct object manipulation whereas calling setState is a function call and doesn't guarantee immediate execution.
However do not use 2nd approach at all because it will create confusion for the next developer who manages such code(In my opinion). In the long run when the data grows you will have to keep a separate state obj for managing the data and the UI.
So it is always better to keep them separate from the beginning.

Update a nested objects in Map Immutable.js

So I am having trouble updating in the reducer with Immutable.js.
So lets say I have a an initial state in my reducer as so:
Immutable.Map(action.someData)
where someData is a JSON, I received from a server:
someData: {
contactInfo: {phoneNumber: 123-1253}
address: 101 e street
family: {
husband: "Bob"
wife: "Sally"
}
}
If I wanted to update the family.husband, how would I go on to do it?
since someData is just a regular object, does this not allow me to use setIn method?
Looking into Immutable documentation, I think the correct way is to create immutable structures on all levels, that is:
Immutable.fromJS(action.someData)
then you will be able to use setIn.
If you keep the internal objects as plain javascript objects, they are still mutable.

Redux-way in the real life

I want to ask the community about an ideological problem.
Lets imagine todo-list on react/redux, you have single state where todoItems array is served. But now lets imagine I want to have few components on the page that are render todoItems with different UI. And I need to update each these components on CRUD of todoItems. What is your architectural approach of this issue? Don't forget we have a large database and we can get todoItems with pagination only.
Update:
Lets make it clear. When we implement redux life cycle with this UI we have 2 options:
1) Serve one array of todoItems into singleton redux state object.
Advantages: all our components will updates by object changing.
Problems: we can't get ALL data from our database, but have to show different paginated/filtered data, so we can't implement pagination/filtering on frontend-side. We have a few different components and the have to render different objects collection. So it doesn't fit.
2) We can use different keys into our global redux state.
Advantages: we can independently get data for each component
Problems: other components will not feel when object changing in one of them. In this case we have to write custom code.
I just want to know maybe I'm missing something and we have other option or maybe someone have good architectural approach to this problem.
I bet your complications come from the point of view which unfortunately quite common among redux community: trying to keep redux shape as close to UI shape as possible.
Try no to think about redux state as a substitute for the Component states. What redux should know about is actual todos only (id, title, date of creation, etc.). Let Component-specific data like pagination stuff live in Components state. When user goes to next page in one of the Components what should be updated is this Component state (pageNumber, from, to, amount, etc.). redux should be updated only in case necessary todos are missing.
The useful analogy is to thinking about your redux as good old SQL-database: redux store state is data itself, selectors and actions are queries and stored procedures, React Components are views with selected data.
Update: Ok, seems like what you are looking for is state normalization. Separate todos details from the lists of ids. This way updates of todo fields will be sensed by all the Components. On the other hand you'll be able to keep separate collections of todos in different Components. Namely make state look like this:
{
funnyTodos: [ 'id1', 'id2' ],
boringTodos: [ 'id3', 'id4' ],
recentlyDoneTodos: [ 'id1' ],
todos: {
id1: { name: .... },
id2: { name: .... },
id3: { name: .... },
id4: { name: .... },
}
}
Implementing pagination in this case is just a matter of getting list of todos ids for the next page from back-end and then loading missing todos for given ids.

How to avoid Immutable.JS functions/accessors inside React components

I'm coding an application using React for UI, Redux to manage the state and Immutable.js to mutate the state, however, I'd like to know how to avoid the use of Immutable.JS accessors in my React components, like get() or getIn().
I believe that using that Immutable.JS accessors will infect my React components. How to avoid that?
I don't think you're going to have much in the way of an option here if you want to keep it immutable. You could convert it toJS, but then you'd be losing the benefits of object identity comparison for re-rendering pure components. Your best bet is probably to hold your nose and pretend it's basically a JavaScript Map.
Aside from that, if you're not attached to Immutable.js, you might consider using something like seamless immutable which behaves a lot more like native JavaScript arrays and objects. Or you could go old-fashioned and just Object.freeze() things yourself.
The way to avoid Immutable.JS accessors and use the dot-notation is using the Record structure from Immutable.JS.
First we must create a template:
const MyTemplate = Record({
id: 0,
name: ''
})
...
case ContentFilterTypes.ADD_ITEM:
return {
listObjects : state.listObjects.push(new MyTemplate({
id: action.item.id,
name: action.item.description,
}))
}
To access it in the presentional, we need only to set the prop that we want to get information, like:
<ContentFilterAvatar id={value.id} name={value.name} />

What is the use of immutable.js while using redux?

This is something I'am not getting right.
While using redux, in reducers we use the spread operator.
For e.g.
{...state,data : action.payload,fetching:false}
That is a new state object is created, rather than mutating the correct state right? (Please correct me if i'am wrong)
In such cases what is the use of immutableJS ??
It performs the same action as mentioned above right??
You are correct, the example you have shown is creating a new object and not mutating the state. It is fine for many cases, so if you don't feel that ImmutableJS is going to add anything for you, don't use it.
ImmutableJS was more useful before the spread operator was in common use in ES6 (I believe it is technically still only a proposal). If you are not using ES6, then the alternative is to use Object.assign which can get very messy, very quickly, especially with more nested structures.
ImmutableJS is still useful if you need to modify a single node deep within the state tree, but if this is the case, you can generally get around it by structuring the data in a different way.
When you have a simple flat state, you can easily manage it without extra libraries.
But let's consider something more complex, like the following
{
users: {
123: {
name: 'John',
lastName: 'Doe'
},
345: {
name: 'Bob',
lastName: 'Jack'
}
....
}
}
If you want to update a name for some user, it will be not so trivial
return {
...state,
users: {
...state.users,
[action.userId]: {
...state.users[action.userId],
name: action.newName
}
}
Pretty much code, isn't it? At this moment, you may want to look for another solution and immutable.js may help you do the same with one line:
state.setIn(['users', action.userId, 'name'], action.newName)
Making your state immutable ensures you that the state will not get modified outside of flux-flow. In very complex structures with a lot of levels and props being passed around it, it prevents the state from being mutated accidentally.

Resources