React redux nested array update good practice and perfs - reactjs

I'have one simple question.
I need to update my redux state. In this state i have an array with object into it. If i need to update the valid property.
(... represent dummy values)
myArray: [
{valid: false, ...},
{valid: false, ...},
...
]
I've seen people using the .map(item, index).
I've seen people using the immutable-helpers
And people doing it with myArray[index] = {myNewObject}.
My question is what's the best in terms of performences and good practice.
The map seems ok for small array but what if i have 12000 items ? The helpers add a library and the last one seems overkill to replace a complete object to update only on attribute of it.
If you have some clue, reading, info it would help me a lot to settle this dilema.
Thank you!

Related

How can I update arbitrarily/dynamically nested data with immutability helper?

To update nested data with immutability helper, you usually hard-code the path to the data you want to update, sometimes with variables for keys. What do you do if the number of keys/indexes (that is, the depth of nesting) is also variable? I'm looking for a way to update data given an arbitrarily long list of keys. Given [0, 1, 1], I want to update data[0][1][1], or given [9], I'd like to update data[9].
Context: I have a deeply nested array of comments, where a nested comment is a reply to its parent, and I need to add/remove/edit comments based on which comment is selected.
It looks like Immutable.js has methods that work just like I'm describing:
Immutable.JS’s get() or getIn() methods … [access] properties via an array of strings, each of which represents a property key.
https://redux.js.org/recipes/using-immutablejs-with-redux#difficult-to-interoperate-with
Is there a good way to do this with immutability-helper? If not, it's not too late for me to switch to Immutable.js.
The helpers can be used on arbitrary objects, not just immutables. These include getIn, setIn, and updateIn:
Take a look at the docs, they are quite convinient and come with samples.
const { getIn } = require('immutable');
const myDynamicPath = [0, 1, 1];
getIn({ 1: { 2: { 3: 123 }}}, [1, 2, '3'], 'ifNotSet') // 123
PS: Take care when using numbers as keys, as they are always strings on objects. ImmutableJS (and native Map/Set) on the other hand can deal with arbitrary types in keys and are therefore type-strict when used on ImmutableJS collections. So if you ever convert that data object to an Immutable, you might have confusing results if you do not pay attention.

How do deal with nested Arrays/objects in BehaviorSubjects, Observables?

I generally have problems using rxjs with nested Objects or Arrays.
My current use-case is this:
{a: [
{b: 0, c:[{d:1}]},
{b: 1, e:[{f: 'someString'}]}
]
Task: Get and set the Observable or value of a,b,c,d,e,f. I also want to be able to subscribe to each property.
I had this Problem in a similar use-case with an Array of BehaviorSubjects:
Efficiently get Observable of an array BehaviorSubjects
I generally have problems to use the basic functionality of nested arrays/objects in rxjs.
The basic functionality I mean includes:
Array:
getting Element by Index
using for of/in on Arrays
setting an Element by Index
push, pop, shift, slice, splice, ...
Object:
getting Value by Property name
going into the nested tree: object.key1.key2.key3[3].key4 ...
setting Value by Property name
assign
for of/in loops
Generally:
Destructuring: e.g.: let [variable1, variable2] = someObject;
Maybe other stuff I forgot.
I dont know if and which functions are possible for which rxjs Objects and which make sense (for example you should be able to set values in an Observable directly). But coming from a background without rxjs, I have trouble to manage my rxjs Objects properly.
I think reason for this besides my lack of knowledge and understanding is, that
a. The rxjs Objects don't provide the functionality as I'm used to from normal arrays and objects. e.g.:
let variable1 = array[1].property;
//becomes this (see related stack-Question I mentioned earlier)
let variable2 = array.pipe(mergeMap(d=> d[index].pipe(map(d1 => d1[property]));
// -> what happens here? You first need to know what mergeMap,
// map is doing and you have 5 levels of nested inline functions.
b. To implement the those mentioned functionalities I need to go over the .pipe() function and use some function like mergeMap, map, pluck, ... Functions that aren't directly indicating that you can get the Observable of let's say 'e' in my example. Making something like object.a[1].e wierd to implement (at least I don't know how to do that yet)
EDIT:
I also want to note, that I still love the idea of rxjs which works well in angular. I just have problems using it to it's full extend, as I'm a bit new to angular and consequently rxjs.
I thin RX is mainly focus on dealing with async operations. Mutation of array and object we can perfectly use the methods comes natively with javascript if theres no existing operators. or you can create your own operator for mutation/iteration etc.
Will try to answer some of your question on array/objects mutation, they are actually very straight forward.
Array:
getting Element by Index
map(arr=>arr[index])
using for of/in on Arrays
map(arr=>arry.map(item=>....))
setting an Element by Index
tap(arr=>arr[index]=somevalue)
Object:
getting Value by Property name
pluck('name')
going into the nested tree: object.key1.key2.key3[3].key4 ...
pluck('key1','key2')
setting Value by Property name
map(obj=>({a:value,obj...}))
assign
lets say your really want some pick array index method as rxjs operator you can create something like, same as for..in operations.
const pluckIndex=(index)=>source=>source.pipe(map(arr=>arr[index]))
const source = of([2,3])
source.pipe(pluckIndex(1)).subscribe(x => console.log(x));

Can TypeScript's `readonly` fully replace Immutable.js?

I have worked on a couple of projects using React.js. Some of them have used Flux, some Redux and some were just plain React apps utilizing Context.
I really like the way how Redux is using functional patterns. However, there is a strong chance that developers unintentionally mutate the state. When searching for a solution, there is basically just one answer - Immutable.js. To be honest, I hate this library. It totally changes the way you use JavaScript. Moreover, it has to be implemented throughout the whole application, otherwise you end up having weird errors when some objects are plain JS and some are Immutable structures. Or you start using .toJS(), which is - again - very very bad.
Recently, a colleague of mine has suggested using TypeScript. Aside from the type safety, it has one interesting feature - you can define your own data structures, which have all their fields labeled as readonly. Such a structure would be essentially immutable.
I am not an expert on either Immutable.js or TypeScript. However, the promise of having immutable data structures inside Redux store and without using Immutable.js seems too good to be true. Is TypeScript's readonly a suitable replacement for Immutable.js? Or are there any hidden issues?
While it is true that the readonly modifier of TypeScript only exists at design type and does not affect runtime code, this is true of the entire type system. That is, nothing stops you at runtime from assigning a number to a variable of type string. So that answer is kind of a red herring... if you get warned at design time that you're trying to mutate something marked as const or readonly, then that would possibly eliminate the need for extensive runtime checking.
But there is a major reason why readonly is insufficient. There is an outstanding issue with readonly, which is that currently (as of TS3.4), types that differ only in their readonly attributes are mutually assignable. Which lets you easily bust through the protective readonly shell of any property and mess with the innards:
type Person = { name: string, age: number }
type ReadonlyPerson = Readonly<Person>;
const readonlyPerson: ReadonlyPerson = { name: "Peter Pan", age: 12 };
readonlyPerson.age = 40; // error, "I won't grow up!"
const writablePerson: Person = readonlyPerson; // no error?!?!
writablePerson.age = 40; // no error! Get a job, Peter.
console.log(readonlyPerson.age); // 40
This is pretty bad for readonly. Until that gets resolved, you might find yourself agreeing with a previous issue filer who had originally named the issue "readonly modifiers are a joke" 🤡.
Even if this does get resolved, readonly might not cover all use cases. You'd also need to walk through all interfaces and types in your libraries (or even the standard libraries) and remove methods that mutate state. So all uses of Array would need to be changed to ReadonlyArray and all uses of Map would need to be changed to ReadonlyMap, etc. Once you did this you'd have a fairly typesafe way to represent immutability. But it's a lot of work.
Anyway, hope that helps; good luck!
The purpose of Immutable.js is not to prevent a developer from doing an illegal mutation at compile time. It provides a convenient API to create copies of an object with some of its properties changed. The fact that you get type safeness on objects that you manage with immutable.js is basically just a side effect of using it.
Typescript is "just" a typing system. It does not implement any of the features Immutable.js does to make copies of immutable objects. All it does, when declaring a variable as readonly, is to check at compile time that you do not mutate it. How you design your code to handle immutability is not the scope of a typing system and you would still need a way of dealing with it.
React ensures immutability by providing a method setState instead of mutating the state object directly. It takes care of merging the changed properties for you. But if you e.g. use redux you may want a convenient solution to handle immutability too. That is what Immutable.js provides and typescript never will and it is independent of whether you like the api or not.
There are two issues with this:
1) You have to use readonly and/or things like ReadonlyArray all the way down, which is error-prone.
2) readonly exists solely at compile time, not runtime, unless backed by immutable data stores. Once your code is transpiled to JS your runtime code can do whatever it wants.
Immutable js distinguishing feature compared to readonly is structural sharing.
Here is general benefit:
Imagine nested JS object that have 16 properties across multiple levels of nesting.
With readonly the way to update a value is to copy old one, modify whatever data we want and then we have new value!
With JS the way to update a value is to keep all the properties that did not change and only copy those that did (and their parents untill we reach a root).
Thus Immutable js saves time on update (less copying), saves memory (less copying), saves time when deciding if we need to redo some related work (e.g. we know that some leafs didn't change so their DOM do not have to be changed by React!).
As you can see readonly is not even in the same league as Immutable js. One is mutation property, the other is efficient immutable data structure library.
Typescript is still rough around the edges with immutability - and they still (as of Typescript 3.7) haven't fixed the issue where you can mutate readonly objects by first assigning them to non-readonly objects.
But the usability is still pretty good because it covers almost all other use cases.
This definition which I've found in this comment works pretty well for me:
type ImmutablePrimitive = undefined | null | boolean | string | number | Function;
export type Immutable<T> =
T extends ImmutablePrimitive ? T :
T extends Array<infer U> ? ImmutableArray<U> :
T extends Map<infer K, infer V> ? ImmutableMap<K, V> :
T extends Set<infer M> ? ImmutableSet<M> : ImmutableObject<T>;
export type ImmutableArray<T> = ReadonlyArray<Immutable<T>>;
export type ImmutableMap<K, V> = ReadonlyMap<Immutable<K>, Immutable<V>>;
export type ImmutableSet<T> = ReadonlySet<Immutable<T>>;
export type ImmutableObject<T> = { readonly [K in keyof T]: Immutable<T[K]> };

What is the name of the anti-pattern of using a js object/dictionary/map to implement an array/vector

For ease of notation, I will use JSON in the following, though the anti-pattern can be programmed in many languages
Let's say that I have a sensible JSON such as
{
"SomeProperty": "SomeValue",
"SomeOtherProperty": 42,
"Items": [
"ValueOfItem0", "ValueOfItem1"
]
}
It has simple entries and an array of items. An alternative way of representing the data, which I think is an anti-pattern and for which I search the name is
{
"someProperty": "someValue",
"someOtherProperty": 42,
"Item0": "valueOfItem0",
"Item1": "valueOfItem1",
"NumberOfItems": 2
}
Instead of by the array, the items are kept 'together' by the keys, which a consumer of the anti-pattern JSON would need to predict. For this reason, the NumberOfItems property has been added, though by using a TryGet-like technique, the property can be made obsolete. Why would anyone do this? Limitations of the serializer.
Comments:
My search has revealed nothing. The sort-of opposite direction is the "Arrject", therefore my humble suggestion for the described anti-pattern, if yet unnamed, would be "Orray", a name already used by Star Wars.

react: Modifying a dictionary inside of a list

I have a state object like
this.state = {
newPerson: '',
people: [{name:'Eric', update: false} , {name:'Rick', update:false}, {name:'Yoni', update:false}]
};
I want to map over the list and be able to modify N object (ie - set status to be true).
I was thinking that I could map over the list of dictionaries by checking to see if the name matches N object's name, then "pop out" / delete the dictionary, modify it and then re-add it.
Is there a better way to do this? Especially following react's "functional" programming style by not modifying a object in space.
You can just map over your people list and modify (merge) only the one that matches the requirement (eg name in your example - it won't affect the original array). But the best way would be indexing your objects in collection and then using map function - you can have duplicated names at some point.
I know it's redux docs, but can help you with your problem - https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns

Resources