user5247234
user5247234

Reputation:

Await window.location.href?

So this might be a weird scenario but I have an endpoint (GET, that returns CSV) which I am calling using window.location.href = "URL". This call can take some time due to the heavy data load and for that reason I would want a loading spinner to appear on the page.

(Using React) At the beginning of the onClick function I am setting the state for the loading spinner to true, calling window.location.href and then setting the state to false.

I have tried everything I could however I can't get the spinner to load and hide properly once the api has completed. I have tried wrapping it in a promise and trying .then but still no luck.

Any ideas? I'm trying to do something like this:

export = () => {

    this.setState({loading:true});

    window.location.href = "url";

    this.setState({loading:false});

}

Upvotes: 6

Views: 6883

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074595

If the page is going to be replaced by the csv...

...then just fix the typo (you have loaction instead of location) and remove this.setState({false}) (which is also a typo, but which you don't want). The spinner will start, probably, and eventually the page will be replaced with the CSV.

If the page is going to remain in place...

...then the way I've done this is to have a cookie that tells me whether the response has been received:

  1. Make sure the cookie isn't set.
  2. Make sure the response sends the cookie.
  3. Use a timer loop in the main page looking for the cookie value.

So in your case, something along the lines of:

export = () => {
    this.setState({loading:true});
    this.clearTheCookieValue();
    window.location.href = "url";
    this.cookieWatchTimer = setInterval(() => {
        if (/*the cookie value has now been set*/) {
            clearInterval(this.cookieWatchTimer);
            this.cookieWatchTimer = 0;
            this.setState({loading: fals});
        }
    });
}

...and in componentWillUnmount, clear that interval timer.

Upvotes: 1

Related Questions