Reputation: 21
I want to remove the items from each of saveProduct
s inside each storeData
object
const initialState = {
storeData: [{
"code": "f1",
"name": "storage-no-1",
"saveProducts": [{
"code": "P1",
"id": "1",
"name": "product-no-1",
"size": 20,
},
{
"code": "P1",
"id": "2",
"name": "product-no-2",
"size": 20,
},
]
},
{
"code": "f2",
"name": "storage-no-2",
"saveProducts": [{
"code": "P1",
"id": "1",
"name": "product-no-1",
"size": 20,
},
{
"code": "P1",
"id": "2",
"name": "product-no-2",
"size": 20,
},
]
},
]
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = initialState;
}
deleteItem(saveProductsId, storeCode) {
this.setState(prevState => {
prevState.storeData.map(store => {
if (store.code == storeCode) {
return {
...store,
saveProducts: [
...store.saveProducts.filter(product => product !== saveProductsId)
]
};
} else {
return store;
}
})
})
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Upvotes: 0
Views: 406
Reputation: 13801
You have 2 issues in your code
1) You are not returning the new state when you are inside the state,
this.setState(prevState => {
return {
here you are actually returning the new state.
so, your code should look like this
this.setState(prevState => {
return {
...prevState, storeData: prevState.storeData.map(store => {
if (store.code == storeCode) {
return {
...store,
saveProducts: [
...store.saveProducts.filter(product => product.id !== saveProductsId)
]
};
} else {
return store;
}
})
}
})
2) You are comparing ...store.saveProducts.filter(product => product !== saveProductsId)
here you need product.id
instead of product
Upvotes: 0
Reputation: 6015
You are not returning the computed result!
deleteItem(saveProductsId, storeCode) {
this.setState(prevState => {
return prevState.storeData.map(store => { // add return on this line
if (store.code == storeCode) {
return {
...store,
saveProducts: [
...store.saveProducts.filter(product => product !== saveProductsId)
]
};
} else {
return store;
}
})
})
};
Upvotes: 1
Reputation: 6393
You need return new state in setState
deleteItem = (saveProductsId, storeCode) => {
this.setState(prevState => {
return {...prevState, storeData: prevState.storeData.map(store => {
if (store.code == storeCode) {
return {
...store,
saveProducts: [
...store.saveProducts.filter(product => product !== saveProductsId)
]
};
} else {
return store;
}
})
}
})
};
Upvotes: 2