0

I have a checkboxes array with boolean values and I want to update its elements on change. Now instead of filled array [false, false, false, false, true] I get [empty × 4, true]

  const [checkboxes, setCheckboxes] = useState([]);
  const [listInfo, setList] = useState([]);

  const getList = async () => {
    const response = await list.get('/list/')
    setList(response.data)
  }
  useEffect(() => {
    const array = []
    getList().then(() => {
      for (let i = 0; i < listInfo.length; i++) {
        array[i] = false
      }
      setCheckboxes(array)
    })
  }, [])

  const handleChangeCheckbox = (event, i) => {
        let isChecked = event.target.checked;
    const array = []
    if (isChecked) {
      array[i] = true
      setCheckboxes(array)
    } else {
      array[i] = false
      setCheckboxes(array)
    }
  }

And I call this function:

<input key={i} type="checkbox" onChange={e => handleChangeCheckbox(e, i)}></input>

How to update elements correctly?

1
  • Use the map() method. This answer should give you an idea of how you could do this. Commented Aug 29, 2021 at 10:37

3 Answers 3

1

You created an empty array and replaced your state, that's why you get [empty × 4, true]

You need to spread your existing state before changing an item inside them:

  const handleChangeCheckbox = (event, i) => {
    const isChecked = event.target.checked;
    const array = [...checkboxes]  // <-- This line
    if (isChecked) {
      array[i] = true
      setCheckboxes(array)
    } else {
      array[i] = false
      setCheckboxes(array)
    }
  }

In your last case, it will be similar to this:

const array = [];
array[3] = true;
console.log(array);

Sign up to request clarification or add additional context in comments.

5 Comments

Isn't he set his setCheckboxes in the useEffect?
oh shoot ! i didn't notice that :-) my bad !
Haha, Not to worries mate. I'd thank you for your last edit. users[0]?.[1]?.items this one.
No need of if-else` statements as well...it's directly provided by isChecked flag.
That's right, but it's good to stick with his original solution but not to mess around his head with a brand new implementation, I guess.
1

You need to create a new array from checkboxes state. You can use array#map to generate new array from checkboxes state and update the state at index i and checked status of checked element.

const handleChangeCheckbox = (event, i) => {
    const isChecked = event.target.checked;
    const newArray = checkboxes.map((val, idx) => idx === i ? isChecked: val);
    setCheckboxes(newArray)
}

Comments

0

To avoid race condition, use useState in following way.

const handleChangeCheckbox = (event, i) => {
  const array = [];
  const isChecked = event.target.checked;

  setCheckboxes((checkboxes) => {
    array = checkboxes.slice();
    array[i] = isChecked;
    return array;
  });
};

1 Comment

this keeps appending true or false to the checkboxes array . But the user wants to update the value of the state based on an index .

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.