The right way to modify an array element and add another in one swoop

4 views
Skip to first unread message

Mike Austin

unread,
Oct 1, 2025, 7:21:29 PM (8 days ago) Oct 1
to PiLuD
const inputValue = items[index].inputValue;

const updatedItems = items.toSpliced(index, 1, {
  ...items[index],
  inputValue: inputValue.slice(0, selectionStart)
}, {
  checkboxValue: false,
  inputValue: inputValue.slice(selectionStart)
});

JavaScript's .splice() or the immutable version, .toSpliced() has always been weird, but is a great fit for modifying one element while adding another. Maybe not the most self-documenting (1 is how many to delete). A little wrapper function could make it better.

I'm always on the lookout for the latest "utilities" library, in the lines of the original, underscore, lodash, Ramda. Now their's es-toolkit, radash, and typedash.

I looked for a simple "remove" element function in es-toolkit but didn't see one. The fewer the libraries, the better anyway.

Mike Austin

unread,
Oct 3, 2025, 7:35:48 PM (6 days ago) Oct 3
to PiLuD
Async events tied to managing data is a nightmare. When you press enter in the middle of text in an input field, and you want to add a new checklist item – you need to sync everything in React perfectly, and then you can't focus on the new item because it doesn't exist yet. So then you keep track of the next index to focus with useEffect().

The main issue was that I use a custom onValueChange() for my Input so it stores state internally until blurred or enter pressed. onKeyDown needs to update that internal value or else it will get out of sync.

Trying to avoid any setTimeout()s, keeping duplicate internal state, not mutating something by accident. I've been working on an off on this Checklist component, and I think it's the most difficult I've ever done. It's not large, just "lots of ins and outs" :)
Reply all
Reply to author
Forward
0 new messages