Can I access state values from children components in an array? - reactjs

I'm very new to React, in the process of learning it for a school project. I've tried searching for this answer thinking it'd be a fairly simple solution, but I'm having trouble finding a result that matches my scenario.
Essentially I'm looking to have an array of a specific component (e.g. Child), each holding a value in their state (e.g. { value: 2 } ). I'm looking to iterate through the array, accessing each component's state.value, and calculate a total from it.
My initial thought was to hold the array in the parent's state, and then iterate through the array doing something like this:
this.state.children.map(child => (
child.state.value
))
However, the result is coming back as 'value' being undefined, leading me to believe I can't access another component's state this way.
I also looked into using refs, as described in the following article:
https://www.geeksforgeeks.org/how-to-access-childs-state-in-react/
However, it seems as though that only lets me create a reference to a single child, meaning I would need a new reference for every child component in the array.
Any advice or sample code of what I could do (the more basic the better) would be greatly appreciated!

Related

Understanding react function notation

Learning react here. Can someone walk me through how to interpret the function below:
const onElementsRemove = (elementsToRemove) => setElements((els) => removeElements(elementsToRemove, els));
As far as I understand it, this is the same as calling:
onElementsRemove(setElements(elementsToRemove(els))?
Is that correct? Is there a benefit to the first notation? Perhaps I am biased coming from the python side of the world but the second one feels more compact? Can someone help me undrstand the reasoning? Thanks!
No, those are not the same. Let's start with the inner part, which needs to be the way it is:
setElements((els) => removeElements(elementsToRemove, els))
When setting state in react, there are two options. You can either directly pass in what you want the new state to be, or you can pass in a function. If you pass in a function, then react will look up what the latest value of the state is, and call your function. Then you return what the new state will be.
So the purpose of doing it this way is to find out what the latest value in the state is. There isn't another way to do this.
Next, the outer part, which has more flexibility:
const onElementsRemove = (elementsToRemove) => /* the stuff we looked at earlier */
This is defining a function called onElementsRemove. From the name, i assume that this is going to be called at some arbitrary point of time in the future. So it's just defining the functionality, and later on you can call it, once you know which elements you want to remove. It will then turn around and set the state. For example, you would do:
onElementsRemove([1, 2, 3]); // i don't actually know what will be in the array
Maybe having this outer function is useful, maybe not. If you're having to do this fairly often it could make sense. In other cases, maybe you could directly call setElements, as in:
setElements((els) => removeElements([1, 2, 3], els));

How to call a variable within a Redux state?

How do I call a variable, such as device_id, device_name, or group_id within the device state in Redux?
{JSON.stringify(device.deviceData)} works great and displays all the state information within deviceData, but {JSON.stringify(device.deviceData.device_id)} doesn't show any information.
Given the 0 pin, I also tried {JSON.stringify(device.deviceData.0.device_id)} but this resulted in an error. I wouldn't want to work with that solution anyway though since I want this call to be universal instead of assigning a specific number in that call.
My Redux state is screenshotted below
deviceData appears to be an array. So you may access the first item like this: device.deviceData[0].device_id
How could I make that universal, in pseudo-terms: device.deviceData[all indexes].device_id if I wanted to make a list of the device_id's for example?
You can use array.map to create a new array with only the device_ids.
const device_ids = device.deviceData.map((data) => data.device_id);

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));

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

why splice not working correctly in react?

I am trying to delete row from my list using delete button .I do like this
if (state.indexOf(action.payload) > -1) {
console.log('iff----')
state.splice(state.indexOf(action.payload), 1);
}
console.log(state)
return state
but it is not deleting the row .here is my code
https://plnkr.co/edit/bpSGPLLoDZcofV4DYxPe?p=preview
Actually using add button I am generating the list of item and there is delete button I am trying to delete item from list using delete button
could you please tell me why it is not working ?
Avoid using Array#splice when working with state in React or Redux. This mutates your state, which you never want to do. Instead, favour immutable methods like Array#slice. e.g.
const index = state.indexOf(action.payload);
if (index === -1) {
return state;
}
return [...state.slice(0, index), ...state.slice(index + 1)];
The flaw of this approach is that in JavaScript, objects and arrays are reference types, so when we get an array, we actually get a pointer to the original array's object managed by react. If we then splice it, we already mutate the original data and whilst it does work without throwing an error, this is not really how we should do it, this can lead to unpredictable apps and is definitely a bad practice. A good practice is to create a copy of the array before manipulating it and a simple way of doing this is by calling the slice method. Slice without arguments simply copies the full array and returns a new one which is then stored. And we can now safely edit this new one and then update to react state with our new array. let me give you and example:
We have an array like this const arr=[1,2,3,4,5]. This is original array.
As I told you before, we can do that like this:
const newVar=arr.slice();
newVar.splice(Index,1);
console.log(newVar);
Or
An alternative to this approach would be to use it a ES6 feature, it is the Spread Operator
Our prior code can be something like this:
const newVar=[...arr]
newVar.splice(Index,1);
console.log(newVar);
That's it. Good luck

Resources