react make setstate synchronous

Solutions on MaxInterview for react make setstate synchronous by the best coders in the world

showing results for - "react make setstate synchronous"
Steve
31 Apr 2017
1class MyComponent extends React.Component {
2
3    function setStateSynchronous(stateUpdate) {
4        return new Promise(resolve => {
5            this.setState(stateUpdate, () => resolve());
6        });
7    }
8
9    async function foo() {
10        // state.count has value of 0
11        await setStateSynchronous(state => ({count: state.count+1}));
12        // execution will only resume here once state has been applied
13        console.log(this.state.count);  // output will be 1
14    }
15} 
16