Very simple. I am making a button to change the state of my parent based on what is entered into an input bar. After the user types a code in and clicks enter a for loop is called which iterates through an array to make sure that the code the user entered is present in the array. If the code is present, this.setState is called and the parent's state is changed.
However, after passing the function from the parent to the button component, if I even type in a string that is in the array into the input field I automatically get an Error: Maximum update depth exceeded saying that the component is repeatedly calling setState -- however, that shouldn't even be possible since I have yet to click the button so the for loop shouldn't even be in use. (well it might be possible I have no clue why it is doing that)
This is the parent:
constructor(props){
super(props);
this.state = {
roomList: [],
activeRoom: undefined
};
this.onUpdateRooms = this.onUpdateRooms.bind(this);
}
//function for changing state
onJoinRoom(roomCode) {
for(let i = 0; i < this.state.roomList.length; i++){
if (this.state.roomList[i].roomCode === roomCode) {
this.setState({activeRoom: roomCode});
console.log('Found')
}
}
}
//within the render
<JoinButton onJoinRoom={this.onJoinRoom}/>
This is my button class:
constructor (props) {
super(props)
this.state = {
enteredCode: ''
}
}
handleInput(e) {
this.setState({enteredCode: e.target.value});
}
handleClick() {
this.props.onJoinRoom(this.state.enteredCode);
}
render() {
return (
<div>
<input
className="roomCodeInput"
type='text'
placeholder='Enter A Room Code'
onChange={this.handleInput.bind(this)}
value={this.state.enteredCode}
/>
<button className="join" onClick={this.handleClick(this)}>JOIN</button>
</div>
);
}
I did a bit of research and people say that one reason for this error is for calling the function within the render method(ie. onClick={this.props.function()} instead of .function without the parenthesis). However, I am using handleClick and binding it so I don't believe my problem is the same. In addition, I need to pass the function parameters so the parenthesis are necessary.
Really confused right now, would love some help :/