I want to duplicate an item with splice but I got problems while changing id. I need different ID for each items but while duplicate, it keeps the same id. Also the id become a number but should be a string.
const duplicateCard = (index, listId) => {
const list = data.lists[listId];
const duplicate_item = list.cards[index];
duplicate_item["id"] = list.cards.length + 1;
list.cards.splice(0, 0, duplicate_item);
const newState = {
...data,
lists: {
...data.lists,
[listId]: list,
},
};
setData(newState);
window.localStorage.setItem("datt", JSON.stringify(newState));
};
Output: The item is duplicated but id is changed for both same items and it becomes integer instead of string
2
Answers
As @cmgchess suggests, this is working:
splice
is a mutable action. In React, you always construct new data –Quite a state nightmare you’ve created for yourself!
You could try to manage it with generic function like
update
–Now your
duplicateCard
function can be improved. NotenewId
is a responsibility of the caller –It’s a big step in the right direction, and maybe you can see a pattern emerging. Still it seems like a lot of effort.
It turns out immutable data structures have well-designed and tested tools to work with them. See libraries like ImmutableJS.