mercredi 1 avril 2020

How do I toggle a check value on prefilled checkboxes?

The checkox lists are from the backend to update and existing article. Using React, redux and express

{categories &&
      categories.map(category => (
        <li key={category._id}>
          <input
            type='checkbox'
            value={category._id}
            onClick={handleToggle(category._id)}
            checked={isChecked(category._id)}
          />
          <label className=''>{category.name}</label> <p>{category._id}</p>
        </li>
      ))}

and some of them are checked depending on the corresponding article

const isChecked = c => {
if (post.categories.findIndex(x => x._id === c) > -1) {
  return true;
} else {
  return false;
}

};

They are prfilled okay but the problem is from here when clicked the checkboxes don't toggle. "true" values stay the same and the "false". In console I can only add more to the array but can't delete from the original prefill.

Here is the handle toggle function

const handleToggle = c => () => {
const clickedCategory = post.categories.findIndex(x => x._id === c);
console.log(clickedCategory, 'index of');
if (clickedCategory === -1) {
  checked.push(c);
} else {
  checked.splice(clickedCategory, 1);
}
console.log(checked, 'checked');
setFormData({ ...formData, categories: checked });

};




Aucun commentaire:

Enregistrer un commentaire