1

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?

2
  • What is the expected output ? Commented Sep 19, 2020 at 16:54
  • 3
    I found out I'm an idiot and it was just because the value is getting passed as a string. So value + 1 = 11. Commented Sep 19, 2020 at 17:00

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.