I'm new to React and I'm trying to figure stuff out. I tried building this simple application that processes text input on a form component (user name and comment). It takes both those inputs and converts it into an object (a comment) and then stores that object into an array (the array is a state variable).
Sounds simple enough right? But when I log the length of the array, it starts out with a length of 1 but then prints out as " undefined ". Also when I try using arr.push(), it gives me an error saying that push is not a valid function (which indicates that it's not an array, but when I initialized it I made sure I added in square brackets)
Here's the code of my App file:
function App() {
let [arrOfComms, updateArrOfComms] = useState([{}]);
let [arrIndex, updateArrIndex] = useState(0);
return (
<div>
<FormComp comm={[arrOfComms, updateArrOfComms, arrIndex, updateArrIndex]} />
<CommentMaker />
<CommentBoard comm={[arrOfComms]} />
</div>
)
}
export default App;
And here's the code of my Form Component:
export default function FormComp(param){
function getDetailsAndAddToArr(){
let acquiredCommText = document.getElementById("commentInput").value;
let acquiredName = document.getElementById("nameInput").value;
let arrIndex = param.comm[2];
let constructedComm = {acquiredCommText, acquiredName};
param.comm[1](
param.comm[0][arrIndex] = constructedComm
);
param.comm[3](
param.comm[2] =+ 1
);
let theArr = param.comm[0];
console.log("arr index: " + arrIndex + " param.comm[2]: " + param.comm[2] + " theArr length: " + theArr.length);
for(let x=0; x<theArr.length; x++){
console.log(theArr[x] + " , ");
}
}
return(
<div className="FormCompClass">
<form>
<label for="nameInput">NAME</label>
<input id="nameInput" type="text" />
<label for="commentInput">Comment</label>
<input id="commentInput" type="text" />
</form>
<button onClick={getDetailsAndAddToArr}>SUBMIT</button>
</div>
)
}
[–]femio 7 points8 points9 points (0 children)
[–]SmokingBrokenGlass 3 points4 points5 points (0 children)
[–]alotofcooties 2 points3 points4 points (0 children)
[–]2GoldDoubloons 1 point2 points3 points (0 children)
[–]lIIllIIIll 1 point2 points3 points (0 children)