I have a very very very deep nested object state.
and i want to change all id properties at once with lodash cloneDeepWith methods.
i'm using cloneDeepWith and only works on first match.
if i dont return the modified object then it won't modifiy anything.
and if i return the value i think the function stops.
the function its working ok but the only problem is that only will run once.
const handleChangeIds = (value) => {
if (value === sections) {
const modifiedObject = cloneDeepWith(value, (sectionsValue) => {
if (sectionsValue && Object.hasOwn(sectionsValue, 'id')) {
const clonedObj = cloneDeep(sectionsValue);
clonedObj.id = generateObjectId();
return clonedObj;
// I Also Tried sectionsValue = clonedObj; its the same behavior
}
});
return modifiedObject;
}
};
const DuplicateSection = () => {
console.log('Original Store', form);
const store = cloneDeepWith(form, handleChangeIds);
console.log('Modified', store)
};
For those who want to achieve same thing like me.
I had a super deep nested object for form. and that form had a repeatable functionality.
and i needed to do two thing in generating another form.
generate new Id for every field Id.
clear the input Value.
I solved my problem like this
and it works perfectly for a super deep nested object.
import cloneDeepWith from 'lodash/cloneDeepWith';
const clearInputAndChangeId = (sections: FormSectionProps): FormSectionProps => {
return cloneDeepWith(sections, (value, propertyName, object) => {
if (propertyName === 'id') return generateObjectId();
if (propertyName === 'selected') return false;
if (propertyName === 'checked') return false;
if (propertyName === 'value') {
if (object.type === 'file') return [];
if (object.type === 'checkbox/rating') return 1;
return '';
}
});
};
Related
I have two states defined like so:
const [productProperties, setProductProperties] = useState<
PropertyGroup[] | null
>(null);
const [originalProductProperties, setOriginalProductProperties] = useState<
PropertyGroup[] | null
>(null);
The first one is supposed to be updated through user input and the second one is used later for a comparison so that only the PropertyGroup's that have changed values will be submitted via API to be updated.
I have done this a thousand times before, but for some reason when I change the name value for a PropertyGroup and update the state for 'productProperties' like so:
(e, itemId) => {
const update = [...productProperties];
const i = update.findIndex((group) => group.id === itemId);
if (i !== -1) {
update[i].name = {
...update[i].name,
[selectedLocale]: e.currentTarget.value,
};
setProductProperties([...update]);
}
}
The state of originalProductProperties also updates. Why? setOriginalProductProperties is never called here, I am also not mutating any state directly and I use the spread operator to be sure to create new references. I am lost.
Preface: It sounds like the two arrays are sharing the same objects. That's fine provided you handle updates correctly.
Although you're copying the array, you're modifying the object in the array directly. That's breaking the main rule of state: Do Not Modify State Directly
Instead, make a copy of the object as well:
(e, itemId) => {
const update = [...productProperties];
const i = update.findIndex((group) => group.id === itemId);
if (i !== -1) {
update[i] = { // *** Note making a new object
...update[i],
[selectedLocale]: e.currentTarget.value,
};;
setProductProperties(update); // (No need to *re*copy the array here, you've already done it at the top of the function)
}
}
Or, since you have that i !== -1 check there, we could copy the array later so we don't copy it if we don't find the group matching itemId:
(e, itemId) => {
const i = productProperties.findIndex((group) => group.id === itemId);
if (i !== -1) {
const update = [...productProperties];
update[i] = { // *** Note making a new object
...update[i],
[selectedLocale]: e.currentTarget.value,
};;
setProductProperties(update);
}
}
FWIW, in cases where you know there will be a match, map is good for this (but probably not in this case, since you seem to indicate the group may not be there):
(e, itemId) => {
const update = productProperties.map((group) => {
if (group.id === itemId) {
// It's the one we want, create the replacement
group = {
...group,
[selectedLocale]: e.currentTarget.value,
};
}
return group;
});
setProductProperties(update);
}
Or sometimes you see it written with a conditional operator:
(e, itemId) => {
const update = productProperties.map((group) =>
group.id === itemId
? { // It's the one we want, create a replacement
...group,
[selectedLocale]: e.currentTarget.value,
}
: group
);
setProductProperties(update);
}
This is my function:
const multiSelect = value => {
let tmpArr = [...selectedPeople];
if (tmpArr.length === 0) {
tmpArr.push(value);
} else {
tmpArr.map(item => {
if (item.id !== value.id) {
tmpArr.push(value);
} else {
return;
}
});
}
setSelectedPeople(tmpArr);
};
I want to check the array for the new value by comparing it with all items. If value === item item the loop function should return, but if the value is not in the array yet, it should push it.
This is a big problem for me but I assume it is a small problem for you guys.
Use Array.every() to check if the array doesn't contain an item with the same id:
const multiSelect = value => {
const tmpArr = [...selectedPeople];
if(tmpArr.every(item => item.id !== value.id)) {
tmpArr.push(value);
}
setSelectedPeople(tmpArr);
};
However, this means that you're duplicating the array needlessly, while causing a re-render, that won't do a thing. So check if the item is already a part of selectedPeople by using Array.some(), and if it does use return to exit the function early. If it's not continue with cloning, and updating the state:
const multiSelect = value => {
if(tmpArr.some(item => item.id === value.id)) {
return;
}
const tmpArr = [...selectedPeople];
tmpArr.push(value);
setSelectedPeople(tmpArr);
};
Use find to check if the item is already in the array. Also, there's no need to make a copy of the source array:
const multiSelect = value => {
if (!selectedPeople.find(item => item.id === value.id))
setSelectedPeople(selectedPeople.concat(value))
}
Another approach.
const
multiSelect = value => setSelectedPeople([
...selectedPeople,
...selectedPeople.some(({ id }) => id === value.id)
? []
: [value]
]);
Array state doesn't change when state change method is beign called :
const [arrayOfDocuments, setArrayOfDocuments] = useState([]);
i tried : setArrayOfDocuments(...[]); or setArrayOfDocuments([]);
where i use my method :
const pushToArrayOfDocuments = (obj) => {
const arr = arrayOfDocuments;
if (obj.filename && obj.file && obj.expiredate && obj.doctype) {
const index = arr.map((e) => e.filename).indexOf(obj.filename);
if (index !== -1) {
arr[index] = obj;
} else {
arr.push(obj);
}
setArrayOfDocuments(arr);
}
};
Maybe the problem is push? and i should do setArrayOfDocuments(...arr); or setArrayOfDocuments(prev => [...prev,...arr]) but if doing so i guess it will go in infinte rendering as i'm passing pushToArrayOfDocuments to the subcomponents.
Like this :
OperatorDocument
key={`Durc${count}`}
title="Durc"
description="Descrizione Durc"
setDocument={pushToArrayOfDocuments}
document={getObjectByName('Durc')}
filedocname="Durc"
/>
edit :
doing like this : setArrayOfDocuments([...arr]);
i get Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
Any help is appreciated.
Firstly, you should never mutate useState's state directly, use them as immutable entities. If you want to use it as initial value, clone it before:
const arr = [...arrayOfDocuments]
// or
const arr = arrayOfDocuments.slice()
Secondly, you are passing the same state array to the setter, then the state will not be updated. Cloning the state will solve this second point.
Finally, the best way to construct a new state from the old value is using a function:
setState(oldValue => (/* construct new state based on old value */))
this will avoid using a value that is not up to date.
At the end, you will have:
const pushToArrayOfDocuments = (obj) => {
if (obj.filename && obj.file && obj.expiredate && obj.doctype) {
setArrayOfDocuments(oldArr => {
const arr = oldArr.slice();
const index = arr.map((e) => e.filename).indexOf(obj.filename);
if (index !== -1) {
arr[index] = obj;
} else {
arr.push(obj);
}
return arr;
}
)
}
};
You need to clone your array before adding it to state.
const arr = arrayOfDocuments.slice();
Full snippet:
const pushToArrayOfDocuments = (obj) => {
if (obj.filename && obj.file && obj.expiredate && obj.doctype) {
const arr = arrayOfDocuments.slice();
const index = arr.findIndex(({ filename }) => filename === obj.filename);
if (index > -1) {
arr[index] = obj;
} else {
arr.push(obj);
}
setArrayOfDocuments(arr);
}
};
I add a similar problem, and I solved by
instead of
const arr = arrayOfDocuments
try spreading the initial array
const arr = [...arrayOfDocuments]
I understand functions need to be pure in order to avoid side-effects. The the following function for example:
//Approach 1
buildValidationErrors(state){
let validationErrors = [];
if(state.name === null)
{
validationErrors.push("Name");
}
if(state.email === null)
{
validationErrors.push("Email");
}
if(state.mobile === null)
{
validationErrors.push("mobile");
}
return validationErrors;
}
//Approach 2
_buildError(state,itemName,validationErrors){
if(state[itemName] === null){
validationErrors.push(itemName);
}
}
buildValidationErrors1(state){
let validationErrors = [];
_buildError(state,"Name",validationErrors );
_buildError(state,"Email",validationErrors);
_buildError(state,"mobile",validationErrors);
return validationErrors;
}
In "Approach 1", you have a long function that builds an array. In "Approach 2" I am extracting the reusable logic to "_buildError" to avoid duplication of logic.
However, in Approach 2, the parameter validationErrors is passed in and it is updated as well causing the function to become 'impure' to my understanding.
From that perspective, can the function be pure and compact?
You can avoid passing the errors array by merging the results outside the _buildError() function:
_buildError(state,itemName){
return state[itemName] === null ? itemName : null;
}
buildValidationErrors1(state){
let validationErrors = [];
validationErrors.push(
_buildError(state,"Name"),
_buildError(state,"Email"),
_buildError(state,"mobile")
).filter((a)=> a !== null);
return validationErrors;
}
However, that does not really change the purity of the function. In your 2nd example, the function depends and change only its parameters, thus it is "pure" enough for automated tests and other practical purposes.
I would consider
_buildError(state,itemName){
return state[itemName] === null ? itemName : null;
}
// reduce if you need more than one thing in the validation array
let validationErrors = ["Name","Email","mobile"]
.reduce((acc,item) => {
if (_buildError(state,item)) acc.push({item,something:state[item].something}); return acc },
[] );
// filter if you just need the item name
let validationErrors = ["Name","Email","mobile"]
.filter(item => _buildError(state,item));
I need to add a property 'sum' to my object while accessing the object using reduce but new property is not getting added when I am doing in react native although when I tried the same thing in jsfiddle it worked fine.
I am thinking if it has to done in a different way in react native.
I tried the same thing in jsfiddle and it worked fine.
const filtered = Object.keys(raw)
.filter(key => {
if (key.includes(cat)) {
return true;
}
if (cat == "all") {
return true;
}
return false;
})
.reduce((obj, key) => {
obj[key] = raw[key];
obj[key].sum = 20;
return obj;
}, {});
Sum property is not getting added in my object in reactnative.
You can try this :
obj[key] = {
...raw[key],
sum: 20
}