Reputation: 487
I know the title is not clear enough but I will try to explain more here. I have a flatlist that I have to select multi Items and create a string value containing the item's id and item's price that I have to send to server. this is my approach: (it work fine)
selectItem = data => {
let test = 130;
if (data.Unites < test) {
data.Etat = 0
console.warn('points insufisants');
} else {
data.isSelect = !data.isSelect;
data.selectedClass = data.isSelect ? StylesGift.validChek : StylesGift.inValidChek;
const newItem = {
idCadeau: data.idCadeau,
Unites: data.Unites,
};
if (data.isSelect) {
const index = this.state.paramsSend.indexOf([newItem]);
this.setState({
paramsSend: this.state.paramsSend.concat([newItem]),
}, () => {
let str = this.state.paramsSend.map(v => Object.values(v).join('_')).join(',')
this.setState({
params: str,
});
});
}else if (data.isSelect === false) {
const index = this.state.paramsSend.indexOf([newItem]);
if (index > -1) {
array.splice(index, 1);
let str = this.state.paramsSend.map(v => Object.values(v).join('_')).join(',')
this.setState({
params: str,
});
}
console.log('looog' + this.state.paramsSend);
}
}
this.setState({changed: !this.state.changer})
};
My probleme is whene I deselect an item I can't remove the item's id and price with this code:
else if (data.isSelect === false) {
const index = this.state.paramsSend.indexOf([newItem]); <-- =-1
if (index > -1) {
this.state.paramsSend.splice(index, 1);
let str=this.state.paramsSend.map(v=>Object.values(v).join('_')).join(',')
this.setState({
params: str,
});
}
console.log('looog' + this.state.paramsSend);
}
any suggestion please ? indexOf return -1 I don't know why
const index = this.state.paramsSend.indexOf([newItem]);
console.warn('index ' + index);
console.warn('from this ' +JSON.stringify(this.state.paramsSend));
console.warn('remove this ' + JSON.stringify(newItem));
newItem is already in paramsSend but it return -1 !
Upvotes: 0
Views: 197
Reputation: 2522
you have 2 issues:
indexOf
with an array, but just with the element you're looking for: const index = this.state.paramsSend.indexOf(newItem);
indexOf(item)
called on an array of objects works only if item
argument is an actual object in the array, not a copy. i.e. this won't work: const index = this.state.paramsSend.indexOf({ idCadeau: 5, Unites: 180 });
even though an identical object exists in the arraySo this should solve both issues:
const index = this.state.paramsSend.findIndex(item => item.idCadeau === newItem.idCadeau)
if (index > -1) {
// good!
}
Upvotes: 1
Reputation: 1634
Your code isn't very clear, but try to use the filter function.
It push in a array all elements matching the condition
const newDataArray = data.filter(elem => elem.idCadeau !== newItem.idCadeau)
So here, you have a new array with all the elements wich are not the same than your newItem
Upvotes: 0