Reputation: 2608
updateDishDetails(id, quantity) {
if (quantity !== 0) {
this.setState(
prevState => ({
bookingFormData: {
...prevState.bookingFormData,
dishDetails: {
...prevState.bookingFormData.dishDetails, // WORKING
[id]: quantity, // PERFECTLY
},
},
})
);
}
if (quantity === 0) {
this.setState(
prevState => ({
bookingFormData: {
...prevState.bookingFormData,
dishDetails: {
// ...prevState.bookingFormData.dishDetails, // NEED HELP HERE
// [id]: quantity, // AND HERE
},
},
})
);
}
}
I have the above function where I set the state of dishDetails based on the value of quantity.
What do I want to achieve?
The relevant state is a follows:
this.state = {
bookingFormData: {
dishDetails: []
}
}
Upvotes: 1
Views: 202
Reputation: 4464
You can use destructuring assignment and the rest operator to create a new object and remove a prop :
if (quantity === 0) {
this.setState(
prevState => {
const { [id]: removedId, ...newDishDetails } = prevState.bookingFormData.dishDetails;
return {
bookingFormData: {
...prevState.bookingFormData,
dishDetails: newDishDetails,
},
},
}
);
}
Upvotes: 3
Reputation: 119
I'll use the delete operator:
if (quantity === 0) {
const dishDetails = {...this.state.bookingFormData.dishDetails}
delete dishDetails[id];
this.setState(
prevState => ({
bookingFormData: {
...prevState.bookingFormData,
dishDetails
}
})
)
}
Upvotes: -1
Reputation: 22323
Set the id's value to null to remove the content.
dishDetails: {
...prevState.bookingFormData.dishDetails,
[id]: null,
},
if its an array thats easier
dishDetails: {
...prevState.bookingFormData.dishDetails.filter((item) => item.id !== id),
},
or if input and output are both objects
dishDetails: {
...Object.entries(prevState.bookingFormData.dishDetails)
.filter(([key, item]) => item.id !== id)
.reduce((acc, [key, item]) => ({...acc, [key]: item}), {}),
},
Upvotes: 0