I have a long running task in Javascript. React should rerender the component on several points between the tasks. But it rerenders only at the end of the whole task. How to make React rerender the page on all setState()
calls?
A simplified example:
setStatePromise = (state) => new Promise(resolve => {
this.setState(state, () => resolve());
});
longRunningTask = async () => {
await this.setStatePromise({progress: 1}); // not shown to the user
await doMuchWork();
await this.setStatePromise({progress: 2}); // not shown to the user
await doEvenMoreWork();
await this.setStatePromise({progress: 3}); // shown to the user when everything is done
};
onButtonClick = async () => {
await this.longRunningTask();
}
Here is a working example showing the problem:
https://codesandbox.io/s/intelligent-cori-31qn5
A workaround I used before is:
setStatePromise = (state) => new Promise(resolve => {
this.setState(state, () => {
setTimeout(() => resolve(), 1);
});
});