I am trying to make a list with an ability to add items to it and modify each item in the list.
The array it uses to make the list is a stateful variable(in this case subjects):
const [subjects, setSubjects] = useState([]);
To manipulate this array, I have a few functions:
function makeItem({ name, id, setActive, changeElement }) {
let boundItemClick = setActive.bind(null, id);
let changeName = changeElement.bind(null, id);
return {
name: name,
id: id,
onClick: boundItemClick,
onChange: changeName
};
}
function addItem( getID, setActive, containerArray, setContainerArray, changeElement) {
setContainerArray([makeItem({ name: "", id: getID(), setActive: setActive, changeElement: changeElement }), ...containerArray]);
}
function getID(array){
return array.length;
}
function changeContainerArray(containerArray, setContainerArray, id, e) {
console.log(id);
console.log(containerArray);
containerArray[id].name = e.target.value;
setContainerArray(containerArray);
}
To make an item, I pass it several components, but the one causing problems here is changeElement. changeElement should take the text present in an input box corresponding to the item, and update the item's name to match what is in the input box. The function changeElement should require the item id so that it knows which item to change, hence I bind it with the item's id and make that a property of item (which I later pass into an input field: onChange={item.onChange}
).
Now, changeElement is itself a bound function that expects a few more components. It stems from the function changeContainerArray:
let changeSubjects = changeContainerArray.bind(null, subjects, setSubjects);
let getNewSubjectID = getID.bind(null, subjects);
let addSubject = addItem.bind(null, getNewSubjectID, setActiveSubject, subjects, setSubjects, changeSubjects);
Here, changeSubjects represents that array. I bind subjects and setSubjects to it, so that it can access and change them. It expects and id and the event, and it will lookup the array element with that id and change its name to the value of the input. Therefore, changeElement is this bound changeSubjects bound again with an item's id.
The problem is that, when I actually try to type something into an item's input(representing its name), the code crashes. I get TypeError: containerArray[id] is undefined
, and, upon further inspection, it turns out that, when I log containerArray, it contains every element in subjects up to id-1. That is, it contains the array subjects at the time that changeElement is bound to id. Clearly, I don't fully understand binding and what problems it could cause, but how could I bind id to changeElement while still retaining subjects as a reference rather than a for some reason copied value?
Please login or Register to submit your answer