Answer the question
In order to leave comments, you need to log in
Unexpected result of a function call. What am I doing wrong?
Problem: When the addEducationDiv function is called, removeEducationDiv is called, and an infinite number of times
class SeekerRegistration extends Component {
constructor(props) {
super(props)
this.state = {
educations: [({section: Education})],
...
}
this.addEducationDiv = this.addEducationDiv.bind(this);
this.removeEducationDiv = this.removeEducationDiv.bind(this);
}
addEducationDiv() {
const educations = [...this.state.educations, {section: Education}]
this.setState({educations});
}
removeEducationDiv({id}) {
console.log('removing...')
const educations = this.state.educations.filter(div => div.id !== id)
this.setState({educations})
}
render() {
const {addEducationDiv, removeEducationDiv} = this
const {educations} = this.state
return <div>
{educations.map((n, i) =>
<div><Education id={n.id}/>
{(i === educations.length - 1) ?
<AddButton addSection={addEducationDiv}/> :
<RemoveButton removeSection={removeEducationDiv(i)}/>}
</div>)}
</div>
}}
const AddButton = ({addSection = f => f}) =>
<button onClick={addSection}>+</button>
const RemoveButton = ({removeSection = f => f, id}) =>
<button onClick={removeSection(id)}>-</button>
Answer the question
In order to leave comments, you need to log in
Now you immediately call removeEducationDiv in the render without waiting for any clicks (you also pass the wrong argument there). It should be like this:
Well, the same error occurs in the RemoveButton component (no arguments are needed at all).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question