Skip to content
Advertisement

Why is slice returning an empty array?

I have a set of booleans.

const [locks, setLock] = useState([false, false, false, false]);

Goal: I am trying to change a value based on the index by slicing the old lock array.

Issue: If the value is 1, the last part of the array (locks.slice(value + 1)) is returning as empty.

Shouldn’t slice returns the selected elements in an array, as a new array object, so it’s not like the locks array is getting changed?

function handleLock(event) {
      const {value} = event.currentTarget;
      const oldLock = locks[value]
      console.log(oldLock)
      const newLocks =  locks.slice(0, value).concat([!oldLock]).concat(locks.slice(value + 1));
      setLock(newLocks)
  }

Broken Down

function handleLock(event) {
      const {value} = event.currentTarget;
      const oldLock = locks[value]
      console.log(oldLock)
      const locks1 = locks.slice(0, value)
      const locks2 = locks.slice(value+1)
      console.log(locks2)
      const newLocks =  locks1.concat([!oldLock]).concat(locks2);
      setLock(newLocks)
  }

Question: What is causing this issue and how do I solve it?

Advertisement

Answer

My guess would be, event.target.value might be returning a string instead of a number. This would cause the sliced value to be an empty array because adding a string to number results in concatenation, not addition.

Try using const value = parseInt(event.target.value, 10);

A suggestion would be to use spread syntax to duplicate the array then assign the value. This should make the code more readable and simpler

const newLocks = [...oldLocks];
newLocks[value] = !newLocks[value];
setLock(newLocks);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement