Issues with Splice
im trying to remove certain object from an array of object, when first object is clicked to remove its removes that object but when i click on second it removes the entire objects from an array.
the issue is most definitely with splice. ANyone knows how to fix this?
7 Replies
The issue is that you start off with
The first removal works fine, it gets data-value 1 then runs
splice(0,1)
which removes the first entry
You're left with
So you click iceymint and it gets data-value
2 then runs splice(2,1)
which removes billy because they're in position 2 now
However this should just leave iceymint behind, but looking at the console log console.log(database.membersList)
is ran twice.
This seems to be because every time you click to intend to delete a user the confirmation button gets another click event listener added. The first delete sets one to remove at index 1, then when you delete the second time there's already a deletion at index 1 with another deletion at index 2
So, to solve this I would instead of storing indexes in data-value
I would store a key for instance it could just be their email. Then rather than use splice use something like
Also move the confirmation click listener to outside so it's only activated once. This leaves the issue of passing which one was clicked to the confirmation box and I'd have an object that relates to the confirmation box contain that value
Or remove the event listener from the confirmation buttonafter deleting the first user im running this again
so data attribute is reset once again
Also for syntax highlighting you want to put the "js" on the same line as ```js
You'll need to replace
with
Or you could give users a unique id and then use that, email was the only thing from the data you provided that was unique. An id would be better.
You can use the uuid library https://www.npmjs.com/package/uuid to do that
npm
uuid
RFC4122 (v1, v4, and v5) UUIDs. Latest version: 9.0.0, last published: 8 months ago. Start using uuid in your project by running
npm i uuid
. There are 53433 other projects in the npm registry using uuid.i will try this.
also im confused when you said i need to confirmation click outside, i did that . it wasnt working anf the value it retuned was undefined
That's because you were passing in value from the first click, but outside value is undefined. You need to pass value some other way
I had this issue, I just used jquery