score:1
Technically you cannot cancel or abort a promise because the web browser does not expose any method for doing that.
What you can do instead is to just ignore the promise if the user navigated to another page. There are two methods to do that:
Using Redux, Thunk, and a promise middleware
You should not store your application state in your component state. By using Redux the application state will be shared amongst all components. Then you use redux-promise-middleware in combination with Thunk middleware to handle async actions in Redux.
Simply, in your action you can do something like this:
case 'LOAD_ORDERS_SUCCESS':
if state.location != 'orders' { return }
// store the data in the application state
Using RxJS and observables
Observables is an alternative way to Promises.
There is a library called redux-observable and a video from Netflix that explain how Observable can be used exactly for this very reason. Check out this recipe in their docs:
const fetchUserEpic = action$ =>
action$.ofType(FETCH_USER)
.mergeMap(action =>
ajax.getJSON(`/api/users/${action.payload}`)
.map(fetchUserFulfilled)
.takeUntil(action$.ofType(FETCH_USER_CANCELLED))
);
score:2
Just think of componentWillUnmount
as an opportunity function. It is your opportunity to do as the docs say, perform any additional clean up that React won't do on its own.
As far as XHR requests go, you would need to have a Promise library that supports cancelling the promise. If the library you use does support that then in the componentWillUnmount
you would just make sure you have access to all Promises and cancel each one.
As far as canceling anything else, you just need to use whatever functions are provided for you to cancel whatever it is you want to cancel. If their is a function to cancel it then use the nature of componentWillUnmount
to do so if you need it to be cancelled if the component is being unmounted.
As an example of how we use it where I'm at: If a component is going to make requests, we set a property on the component that is an array and holds all the requests. we would call this this.statePromises
. Whenever we make a request/Promise we would push that Promise into the this.statePromises
. In the componentWillUnmount
we have the following
componentWillUnmount() {
this.statePromises.forEach(p => p.cancel());
}
p being a promise. This only works because of the library, bluebird, that we use for our promises. But that should give you an idea of how you could use componentWillUnmount
to do any additional clean up.
Source: stackoverflow.com
Related Query
- How to cancel ALL requests in ComponentWillUnmount?
- How to cancel a fetch on componentWillUnmount
- Cancel All Subscriptions and Asyncs in the componentWillUnmount Method, how?
- Next.JS: How to make ALL requests server-side
- Does anyone have this issue? "To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method"
- How to cancel all subscriptions inside UseEffect in React
- AXIOS: how to run http requests concurrently and get the result of all requests event if a request fails
- how to redirect all server requests to index.html file in node.js
- Cancel all subscriptions and asynchronous tasks in the componentWillUnmount method
- Cancel separate and all axios requests
- How can I handle simultaneous requests for authenticated API, pause all but first while it fetches new access token?
- React: how to display success message if all requests were successful in a loop
- How to Resolve Memory Leak and Cancel All Subscriptions Error in React App?
- How to cancel all subscriptions and asynchronous tasks in a useEffect cleanup function?
- React-Redux: How to ensure that multiple fetch requests are all successfully made before an action is dispatched
- How to cancel cancel all subscriptions and asynchronous tasks?
- how to cancel web requests using interceptors?
- How create universal fetcher for all requests in client and server(getInitialProps)
- cancel all subscriptions in componentWillUnmount
- How to cancel the RTK-Query requests
- How to set an Authorization Header for all requests under a sub-url in React App
- Unable to cleanup useEffect, how can I cancel all asynchronous tasks when unmounting my component?
- How to cancel axios requests
- How to cancel subsequent requests in axios interceptor?
- How to intercept all AJAX(xhr and fetch) requests via javascript?
- Attach Authorization header for all axios requests
- How to select all text in input with Reactjs, when it focused?
- How can I reset a react component including all transitively reachable state?
- How to make Jest wait for all asynchronous code to finish execution before expecting an assertion
- How to add padding and margin to all Material-UI components?
More Query from same tag
- when using create-react-app dependencies @testing-library could not resolve
- How to fix prettier config in vuexy project with react?
- I want to map my array from an object using react and next.js, it's a function component using hooks
- createBrowserHistory is undefined in history import for React Router DOM
- Submit forms data in react
- I don't know how to change the status of a modal
- Session timer in ReactJS
- React js:component needs browser-reload to show updated content
- creatable props not working in react-virtualized-select component
- Test connected component in React/Redux
- ReactJS concurrent SetState race condition
- setInterval is running after the page is change
- How do i pass a route parameter value to both my header component and page content component in react?
- Exporting Colors In React using TypeScript
- React - translations per component
- useSelector() not re-rendering component on update
- How to use dynamic meta tags in react single page application?
- how to pull 1 button to the left and 2 button to the right in react>
- React.js - passing functions between components using Context API - not working
- Getting the max for an Api json data in react
- CK Editor (Version 5) paste screenshot not working for react js
- Using React Hooks only; incre and decre the count asynch after 1 second you click the button
- ReplaceReducer causing unexpected key error
- Connection refused on react docker container
- TypeError passing a function to a React click handler
- React: Best way to pass Firestore info to components?
- React dynamic routes based on json data
- React then returns cannot read property of undefined
- ReactJS: Uncaught ReferenceError: require is not defined
- How to check if object contains a string value?