Skip to content

Instantly share code, notes, and snippets.

@isabellachen
Created November 12, 2019 10:02
Show Gist options
  • Save isabellachen/4fbf1c3c51a8b74f9a5662a7f32f64aa to your computer and use it in GitHub Desktop.
Save isabellachen/4fbf1c3c51a8b74f9a5662a7f32f64aa to your computer and use it in GitHub Desktop.
Abort request on navigate in React
import { cid, useInject } from 'inversify-hooks';
import React, { Suspense, useEffect } from 'react';
import { Redirect, Route, Switch, useHistory } from 'react-router-dom';
import { exampleModule } from './example';
import { IHttpService } from './shared';
import { styleGuideModule } from './style-guide';
let didTheUserNavigatedForTheFirstTime = false;
export default function AppRouter() {
const history = useHistory();
const [httpService] = useInject<IHttpService>(cid.IHttpService);
useEffect(() => history.listen(() => abortCurrentRequests), [abortCurrentRequests, history]);
const LoadingMessage = () => <div>Loading..</div>;
function abortCurrentRequests() {
setTimeout(() => (didTheUserNavigatedForTheFirstTime = true));
if (history.action === 'POP' || !didTheUserNavigatedForTheFirstTime) {
return;
}
httpService.resetCancelTokens();
}
return (
<Suspense fallback={<LoadingMessage />}>
<Switch>
<Route exact={true} path="/" render={() => <Redirect to="/example" />} />
{exampleModule.routes}
{styleGuideModule.routes}
</Switch>
</Suspense>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment