I have a child component with a form. When a user submits the form I need to update the state in my top level component.
From reading the docs I belive the correct way is to create a function to update the state in the parent component, and then pass it down to the child component via props where it is executed.
In my child component:
submit(e) {
e.preventDefault();
const setLength = parseInt(this.setLength.value.slice(0, -1));
const restLength = parseInt(this.restLength.value.slice(0, -1));
const noOfSets = parseInt(this.noOfSets.value);
const noOfRounds = parseInt(this.noOfRounds.value);
this.props.run(setLength, restLength, noOfSets, noOfRounds);
}
In my parent component:
run(setLength, restLength, noOfSets, noOfRounds) {
this.setState({
setLength,
restLength,
noOfRounds,
noOfSets,
setTimeRemaining: setLength,
restTimeRemaining: restLength,
currentSet: 1,
currentRound: 1,
resting: false
}, () => {
this.updateProgress('running');
});
}
render() {
return (
<Child run={this.run}/>
My code above works but seems very prone to bugs to me. If I change the order of setLength, restLength, noOfSets, noOfRounds
in either function then the wrong values will be set. Should I therefore be passing an object with key value pairs? Or have I fundamentally gone about this the wrong way