0
I have a problem trying to remove a specific element from AsyncStorage
, is always being removed first element.
Adding element:
async function adicionar() {
if (produto === '') {
alert('Informe um item antes de prosseguir!');
return;
}
if (valor === '' || valor === null) {
setValor(0);
} else {
try {
let lista = {
id: Math.floor(Math.random() * 65536),
produto,
quantidade: parseInt(quantidade),
valor: parseFloat(valor).toFixed(2).replace('.', ','),
valorTotal: parseFloat(quantidade * valor)
.toFixed(2)
.replace('.', ','),
};
const data = (await AsyncStorage.getItem('items')) || '[]';
let items = JSON.parse(data);
//let items = [];
items.push(lista);
await AsyncStorage.setItem('items', JSON.stringify(items)).then(() => {
setProduto('');
setQuantidade('');
setValor('');
console.log(items);
});
} catch (error) {
console.log(error);
}
}
}
Loading the elements:
async function getItems() {
try {
const lista = await AsyncStorage.getItem('items');
const data = JSON.parse(lista);
let total = data.reduce(
(acc, objeto) => acc + parseFloat(objeto.valorTotal),
0,
);
let totalQtd = data.reduce(
(acc, objeto) => acc + parseFloat(objeto.quantidade),
0,
);
setTotal(total);
setTotalQtd(totalQtd);
setData(data);
console.log(lista);
} catch (error) {
console.log(error);
}
}
Removing the element:
async function handleDelete(index) {
try {
const lista = await AsyncStorage.getItem('items');
const data = JSON.parse(lista);
data.splice(index, 1);
await AsyncStorage.setItem('items', JSON.stringify(data));
getItems();
console.log(data);
} catch (error) {
console.log(error);
}
}
async function deleteItem(item) {
try {
var index = data.filter((item) => item.id !== id);
console.log('produto: ' + item.produto); // retorna o nome do produto referente ao id, por exemplo macarrão, ou seja o filter está funcionando.
data.splice(index, 1); // mas ainda está removendo o primeiro item da lista
AsyncStorage.setItem('items', JSON.stringify(data));
} catch (error) {
console.log('error: ', error);
}}
What is the value of
index
? Where Voce uses the functionhandleDelete
, What value did you pass to her? Are you removing the previous item you want to remove? It is not possible to understand the error without further details, but it may be because of the value ofindex
.– Cmte Cardeal
My dear, I am calling the function through the Flatlist, created a button (<Touchableopacity onPress={() => handleDelete(item)}>) that calls the function. It is said to delete an item from the list, but remove the previous one.
– Wander Augusto
I don’t know if it makes a difference, but when you add items, the array is saved as follows: [{"id":15321,"product":"rice","quantity":2,"value":"3,00","valueTotal":"6,00"},{"id":16715,"product":"feijao","quantity":2,"value":"1,00","valueTotal":"2,00"},{"id":39909,"product":"macarrao","quantity":3,"value":"2,00"valueTotal":"6,00"}]
– Wander Augusto
I added the rice first, then the beans and finally the pasta. When I say delete the beans, the rice is removed.
– Wander Augusto
I understood then the value of
index
would then, for example, this object{"id":16846,"produto":"arroz","quantidade":1,"valor":"2,00","valorTotal":"NaN"}
? 'Cause if it is, it’s gonna be a mistake, becauseindex
has to be a number.– Cmte Cardeal
So I’m creating array incorrectly, this is it?
– Wander Augusto
My dear, I thought the index was the id of each object.
– Wander Augusto
No, but if the structure that Voce showed has a
id
unico, Voce could filter array items byid
with the methodfilter()
. This would be, in my opinion, the best way to remove a specific element from an array.– Cmte Cardeal
Got it!!! Blz, I’m going to try it here. It was totally worth it!
– Wander Augusto
@Wanderaugusto Index (or index) is the position of each element in the array, starting at
0
. For example,[a, b, c, d , e, f, g]
have respectively the indexes[0, 1, 2, 3, 4, 5, 6]
.– Rafael Tavares
Right @Rafaeltavares, but still not understood why is removing the last item added in the list. As you said the index is the position of each element in the array, I am trying to remove for example the index element 2, which in the example above refers to "noodles", but is removing the index 0 which is "rice". Did you manage to discover the error? Expensive something so simple that I stopped, has several days and nothing. I studied in these days a lot about array but without success.
– Wander Augusto
@Cmtecardeal has already explained that you are not passing the index. And if an invalid index is passed (your case), the
splice
will start at the beginning of the array, so first item is removed. By the way, I don’t understand why in the question you say last item and here in the commentary is the first item– Rafael Tavares
mal aí @Rafaeltavares, I misspelled the question. It is the Cmtecardeal directed to use the filter but also could not. I’m reviewing the way I created the array.
– Wander Augusto