How to useState to update mutiple items in an array of objects? - reactjs

let initialData = [
{ id: 1, value: "EXPLORER", status:false, name:'explorer'},
{ id: 2, value: "YIDINJI-ADMIN", status:false, name:'yidinji' }]
let [data,setData] = useState(initialData)
The above give data is my initial state of array, Sometimes I have to update multiple items using a single map function
let newData = await data.map(item => {
(item.id === 1)? {...item, status : true} : item;
(item.id === 2)? {...item, status : true} : item;
})
setData(newData)
I have tried multiple ways to update the status of two data in a single map function, but nothing is working. Help will be appreciated!

You forgot return in map. Just add return like this:
let newData = await data.map((item) => {
return item.id === 1 ? { ...item, status: true } : item;
});
setData(newData);
Update, if you want update multyiple items, you can do like this:
let newData = await data.map((item) => {
let result = item;
if (item.id === 1 || item.id === 2) {
result = { ...item, status: true };
}
return result;
});
setData(newData);

This will help you. You forgot to return item.
let newData = data.map(item => {
if (item.id === 1 || item.id===2){
item.status=true
}
return item
})

Related

this.setState isn't making changes in state

I am using functions that change a value in a nested object in the state :
an I am calling those functions in a button , they are executed when I click on that button , but one of those functions doesn't make changes to the state
This is the state :
state = {
data: {
attributesLength: this.props.product.attributes.length,
modalMessage: "",
isOpen: false,
},
};
and these are the functions :
addToCart = (id) => {
let data = { ...this.state.data };
if (Object.keys(this.state).length === 1) {
data.modalMessage = "Please, select product attributes";
this.setState({ data});
return;
}
if (
Object.keys(this.state).length - 1 ===
this.state.data.attributesLength
) {
const attributes = Object.entries(this.state).filter(
([key, value]) => key !== "data"
);
if (this.props.cartProducts.length === 0) {
this.props.addItem({
id: id,
quantity: 1,
attributes: Object.fromEntries(attributes),
});
data.modalMessage = "Added to cart !";
this.setState({ data });
return;
}
const product = this.props.cartProducts.filter((item) => item.id === id);
if (product.length === 0) {
this.props.addItem({
id: id,
quantity: 1,
attributes: Object.fromEntries(attributes),
});
data.modalMessage = "Added to cart !";
this.setState({ data });
return;
}
if (product.length !== 0) {
this.props.changeQuantity({ id: id, case: "increase" });
data.modalMessage = "Quantity increased !";
this.setState({ data });
return;
}
if (this.state.data.attributesLength === 0) {
this.props.addItem({
id: id,
quantity: 1,
attributes: Object.fromEntries(attributes),
});
data.modalMessage = "Added to cart !";
this.setState({ data });
return;
}
} else {
data.modalMessage = 'please, select "ALL" product attributes!';
this.setState({ data });
}
};
changeModalBoolean = () => {
let data = { ...this.state.data };
data.isOpen = !data.isOpen;
this.setState({ data });
};
and this is where I am calling functions :
<button
className={product.inStock ? null : "disabled"}
disabled={product.inStock ? false : true}
onClick={() => {
this.addToCart(product.id);
this.changeModalBoolean();
}}
>
{product.inStock ? "add to cart" : "out of stock"}
</button>
NOTE
changeModalBoolean function works and change state isOpen value,
this.addToCart(product.id);
this.changeModalBoolean();
This code run synchronously one after the other. In every function, you create a copy of previous state let data = { ...this.state.data };
so the this.changeModalBoolean(); just replace state which you set in this.addToCart(product.id); to fix this problem, use this.setState((state) => /*modify state*/)
changeModalBoolean = () => {
this.setState((state) => {
let data = { ...state.data };
data.isOpen = !data.isOpen;
return { data };
})
};
or modify the same object in both functions

How to use "if" inside useState prevState map

Does anybody know how can i use if statement like this.
This example doesnt work
uppy.on('complete', (result) => {
result.successful.forEach((file) =>
setImgs((prevState) =>
prevState.map((item) => {
if(item.id === file.id) {
return {
...item,
image: file.preview
}
}
})
)
)
})
And this works, but there s no if
uppy.on('complete', (result) => {
result.successful.forEach((file) =>
setImgs((prevState) =>
prevState.map((item) => ({
...item,
image: file.preview,
}))
)
)
})
I don't think you need to map if you're just trying to find an item.
You could do
const item = prevState.find(x.id ==> file.id)
return item? {...item.image:file.preview} : null
"doesn't work" will need more specification. Out of observation I can tell that it needed to have else statement or without, in order to return item if no change is required. The variable - item is unchanged element of imgs array, which we put back.
This is after refactoring your pseudocode:
uppy.on("complete", (result) => {
result.successful.forEach((file) =>
setImgs((prevState) =>
prevState.map((item) => {
if (item.id === file.id) {
return { id: item.id, image: file.preview };
} else return item;
})
)
);
});
Check the sandbox here
Since you are using a map that returns a new array, also you are trying to add an image key to the matched item only then, you need to also return for the else case.
const data = state.map((item) => {
if (item.id === file.id) return { ...item, image: file.preview };
return item;
});

REACT UPDATE A DATA

I have a problem trying to update an Array of Objects that lives in a Themecontext, my problem is with mutation, I'm using Update from Immutability helpers. the thing is that when I update my array in my specific element, This appears at the end of my object.
This is my code:
function changeValueOfReference(id, ref, newValue) {
const namevalue = ref === 'colors.primary' ? newValue : '#';
console.warn(id);
const data = editor;
const commentIndex = data.findIndex(function(c) {
return c.id === id;
});
const updatedComment = update(data[commentIndex], {styles: { value: {$set: namevalue} } })
var newData = update(data, {
$splice: [[commentIndex, 1, updatedComment]]
});
setEditor(newData);
this is my result:
NOTE: before I tried to implement the following code, but this mutates the final array and break down my test:
setEditor( prevState => (
prevState.map( propStyle => propStyle.styles.map( eachItem => eachItem.ref === ref ? {...eachItem, value: namevalue}: eachItem ))
))
Well, I finally understood the issue:
1 - commentIndex always referenced to 0
The solution that worked fine for me:
1 - Find the index for the Parent
2 - Find the index for the child
3 - Add an array []
styles : { value: {$set: namevalue} } => styles :[ { value: [{$set: namevalue}] } ]
Any other approach is Wellcome
Complete Code :
function changeValueOfReference(id, referenceName, newValue) {
const data = [...editor];
const elemIndex = data.findIndex((res) => res.id === id);
const indexItems = data
.filter((res) => res.id === id)
.map((re) => re.styles.findIndex((fil) => fil.ref === referenceName));
const updateItem = update(data[elemIndex], {
styles: {
[indexItems]: {
value: { $set: namevalue },
variableref: { $set: [''] },
},
},
});
const newData = update(data, {
$splice: [[elemIndex, 1, updateItem]],
});
setEditor(newData);
}

How to solve Error Use object destructuring prefer-destructuring - React

I am stuck with an ugly issue which I am unable to resolve. I am beginner in React.
This is my Code
handleCheckChildElement(event) {
let items = this.state.items;
items.forEach(items = () => {
if(items.value === event.target.value) {
items.isChecked = event.target.checked;
}
});
this.setState({ items });
}
This is the image of the error -
Use below code for line #55 :
let {items}= {...this.state};
Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
Your code can be improved to something like below. Please find relevant comments in the code below for your better understanding
handleCheckChildElement(event) {
const { items } = this.state; //extract state values like this to a const variable
const newItems = items.map(item => { //do map on items because map returns a new array. It’s good practice to use .map than forEach in your case
if(item.value === event.target.value) {
item.isChecked = event.target.checked;
return item; //return updated item object so that it will be pushed to the newItems array
}
return item; // return item because you need this item object as well
});
this.setState({ items: newItems}); //finally set newItems array into items
}
handleCheckChildElement(event) {
const items = this.state.items;
const filtered = items.filter(item => item.value === event.target.value)
.map(item => item.isChecked = event.target.checked) ;
this.setState({items : [...filtered] );
}

Mutable version of the filter function to filter results in React?

I have a function called renderExercises which I call in my render function. renderExercises returns an array of ExercisesChoose components.
renderExercises() {
const {selectedType} = this.state;
const allExercises = this.props.exercises;
let exercisesToRender = [];
if (selectedType !== 'all') {
exercisesToRender = allExercises[selectedType];
} else {
exercisesToRender = Object.values(allExercises)
.reduce((array, subarray) => array.concat(subarray), [])
.sort();
}
return exercisesToRender.map((exercise) => {
return (
<ExercisesChoose
key={exercise}
name={exercise}
/>
)
})
}
So far this works. However I also want to filter based on search text if the user has entered this text.
This isn't working as filter can't be called on the existing array exercisesToRender.
if (typeof this.searchText !== 'undefined') {
const searchText = this.searchText.value;
// This is not working
exercisesToRender.filter(item => {
return item.includes(searchText);
});
}
What is the solution to this? Is there a sort method that allows for mutation? If so, is this advisable to use?
This is my current solution which works but is pretty ugly:
renderExercises() {
const {selectedType} = this.state;
const allExercises = this.props.exercises;
let exercisesToRender = [];
if (selectedType !== 'all') {
exercisesToRender = allExercises[selectedType];
} else {
// Combine all the different exercise groups into a single array
exercisesToRender = Object.values(allExercises)
.reduce((array, subarray) => array.concat(subarray), [])
.sort();
}
let render = [];
if (typeof this.searchText !== 'undefined') {
const searchText = this.searchText.value;
render = exercisesToRender.filter(item => {
return item.includes(searchText);
});
} else {
render = exercisesToRender;
}
return render.map((exercise) => {
return (
<ExercisesChoose
key={exercise}
name={exercise}
/>
)
})
}
This is what my exercises object looks like:
this.props.exercises = [
legs:["Squat", "Power squats", "Burpees"]
pull:["Pull up", "Chin up", "Dumbbell curl", "Horizontal row"]
push:["Push up", "Bench press", "Dumbbell bench press", "Mountain climbers"]
cardio: ["Running high knees", "Plank", "Crunches", "Skipping"]
]
My strategy for this case would be:
reduce to filter exercises by type
filter them by searchText
sort
map to render
Final result:
renderExercises() {
const { selectedType } = this.state
const { exercises: allExercises } = this.props
return Object
.keys(allExercises)
.reduce((result, key) => {
if (selectedType === 'all' || key === selectedType) {
return [
...result,
...allExercises[key],
]
}
return result
}, [])
.filter(exercise => searchText ? exercise.includes(searchText) : true)
.sort()
.map(exercise =>
<ExercisesChoose
key={exercise}
name={exercise}
/>
)
}
const exercises = {
legs:["Squat", "Power squats", "Burpees"],
pull:["Pull up", "Chin up", "Dumbbell curl", "Horizontal row"],
push:["Push up", "Bench press", "Dumbbell bench press", "Mountain climbers"],
cardio: ["Running high knees", "Plank", "Crunches", "Skipping"],
}
const filterExercises = (type, searchText) => {
return Object
.keys(exercises)
.reduce((result, key) => {
if (type === 'all' || key === type) {
return [
...result,
...exercises[key],
]
}
return result
}, [])
.filter(exercise => searchText ? exercise.includes(searchText) : true)
.sort()
.join(', ')
}
console.log('All exercises:', filterExercises('all', ''))
console.log('All (up):', filterExercises('all', 'up'))
console.log('Push:', filterExercises('push', ''))
console.log('Push (press):', filterExercises('push', 'press'))
Ive expanded slightly on mersocarlin's answer as I was getting some false results from searchText, but essentially his logic does work.
renderExercises() {
const {selectedType} = this.state;
const allExercises = this.props.exercises;
let searchText = false;
if (this.searchText && this.searchText.value.length > 0) {
searchText = this.searchText.value.toLowerCase();
}
return Object
.keys(allExercises)
.reduce((result, key) => {
if (selectedType === 'all' || key === selectedType) {
return [
...result,
...allExercises[key]
]
}
return result
}, [])
.filter(exercise => searchText ? exercise.toLowerCase().includes(searchText) : true)
.map((exercise) => {
let active = false;
if (this.props.chosenExercise === exercise) {
active = true;
}
return (
<ExercisesChoose
key={exercise}
name={exercise}
active={active}
setNumber={this.props.number}
updateValue={this.props.updateValue}
/>
)
})
}

Resources