0
votes

I create a calendnar app with the ability to add notes. Trying to realize the function of adding notes i create some Parent component which has own state timeStart which then passed to child component. Child component should accept props from ParentComponent execute time1:this.props.timeStart in the constructor. But due to the fact that the setState function asynchronous ChildComponent does not have time to wait for props from ParentComponent.

How i can to set initial state of ChildComponent waiting for props from ParentComponent (in other words synchronously)?

ParentComponent:

class ParentComponent extends React.Component {

 constructor() {
    super();
    this.state = {
        timeStart:'00:00',
 };

 render(){

    //some code for changing this.state.timeStart

    return (<ChildComponent timeStart={this.state.timeStart}/>);
 }
}

ChildComponent:

class ChildComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            time1:this.props.timeStart,
            time2:'00:00',
        };
        this.onTime1Change = this.onTime1Change.bind(this);
        this.onTime2Change = this.onTime2Change.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onSubmit(event){
        let el ={
            task:this.state.task.slice(),
            time1:this.state.time1.slice(),
            time2:this.state.time2.slice()
        };
        events.push(el);
        event.preventDefault();
    }


    onTime1Change(event){
        this.setState({time1: event.target.value});
    }

    onTime2Change(event){
        this.setState({time2: event.target.value});
    }

    render() {
        return (
            <div className="form">
                   <form onSubmit={this.onSubmit}>
                    <p><label><input type="time" step="3600" name="time1" value={this.state.time1}
                                                           onChange={this.onTime1Change}/></label>
                       <label><input type="time" step="3600" name="time2" value={this.state.time2}
                                                       onChange={this.onTime2Change}/></label></p>

                    <p><input type="submit" value="Submit" /></p>
                </form>
            </div>
        );
    }
}

export default ChildComponent;
1
thank you too, checked itdiesel94
Glad to have helped.Shubham Khatri
I know. Have already upvoteddiesel94

1 Answers

1
votes

you can use the lifecycle method getDerivedStateFromProps of a component to achieve it.

more details available here Detail