0

I have a function that makes many calculations on the frontend site of react app and there is no option to move it to the backend. As a result, running this function lags a whole app for a few seconds and shows no message whatsoever. I was wondering what is the simplest way to move this function to the background and show a spinning circle on the screen while it's making the calculations. It probably might involve using some async-await approach but I didn't succeed with these.

I tried using setState to set a variable like spinner: true and then making a callback which would make these calculations, and reset the spinner to false, but it didn't work, something like this:

render() {
    return <>
        <SomeSpinner visible={this.state.spinner}/>
    </>
}

this.setState({spinner: true }, () => {
    calculateComplicatedStuff();
    this.setState({spinner: false});
});
skazy
  • 1

1 Answers1

0

I believe the correct way to go about it is making the function itself returns a promise that way you can do something like this

 calculateComplicatedStuff().then(res => this.setState({spinner: false}));
 OR
 await calculateComplicatedStuff();
 this.setState({spinner: false});

So at the initial state the spinner will be true and on the componentDidMount lifecycle method you will call your function asynchronously.

Note: componentDidMount isn't async by default but you can do it like answered here And I think you already know this but expensive calculations shouldn't be made on the client side due to device limitations

Hope this helps

Ali Osman
  • 53
  • 7