Ad

React: Is It Possible To Stop Code 'reading' Until Component Will Receive New Props?

- 1 answer

I have a component, that has button that creates newType on click and sets it to state. types comes from outside from parent component. How can I stop running the code at the moment when this.props.onCreateClick(this.state.selectedDate) runs and wait until I receive updated types so when I get updated types I could run next line?

It's class component. That button is inside Props example: props: types = [{id: 1, name: 'One'}, {id: 2, name: 'Two'}]

this.state = {
   selectedDates: [Date], 
   currentType: null, 
}

<button
    onClick={(e) => {
        this.props.onCreateClick(this.state.selectedDate)
        let newType = this.props.types[this.props.types.length - 1]; 

        this.setState({
            selectedDates: [], 
            currentType: newType.id
        })
    }}

>Create</button>
Ad

Answer

I suggest to use Promise

this.state = {
   selectedDates: [Date], 
   currentType: null, 
}

<button
    onClick={() => {
        this.props.onCreateClick(this.state.selectedDate).then(types => {
            let newType = types[types.length - 1]; 

            this.setState({
                selectedDates: [], 
                currentType: newType.id
            });
        }).catch(error => {
            //handle error
        });

    }}

>Create</button>

And onCreateClick function return Promise which reslove new types you recieve and then you process them in state of you component.

If you wish you could change this code to async\await, same work with promises.

Ad
source: stackoverflow.com
Ad