I am using react
, redux
and react-router
. One of my page is making an API request and showing the data. It works fine. What I want to know is, if the API request is not yet finished, and the user navigates to another route, I want to be able to abort the request.
I am assuming I should dispatch some action in the componentWillUnmount
. Just not able to understand how will it work. Something like...
componentWillUnmount() {
this.props.dispatch(Actions.abortRequest());
}
And I'll store the xhr
reference somewhere in the action. Not sure if this is the correct approach or not (I think not), can someone point me in the right direction?
React Router have a great online documentation portal available, upon a quick search we find the <Prompt /> method. Prompt the user before navigating away from a page.
Sometimes you may want to prevent the user from leaving a screen, for example, if there are unsaved changes, you might want to show a confirmation dialog. You can achieve it by using the beforeRemove event. The event listener receives the action that triggered it.
You can wrap XItem component with React. memo: const XItem = (props) => { ... } const areEqual = (prevProps, nextProps) => { /* Add your logic here to check if you want to rerender XItem return true if you don't want rerender return false if you want a rerender */ } export default React.
I don't think storing xhr
in action is correct.
Actions should be serializable, and XMLHttpRequest definitely isn't.
Instead, I'd use Redux Thunk to return a custom object from my action creator, and do something like this:
function fetchPost(id) {
return dispatch => {
// Assuming you have a helper to make requests:
const xhr = makePostRequest(id);
dispatch({ type: 'FETCH_POST_REQUEST', response, id });
// Assuming you have a helper to attach event handlers:
trackXHR(xhr,
(response) => dispatch({ type: 'FETCH_POST_SUCCESS', response, id }),
(err) => dispatch({ type: 'FETCH_POST_FAILURE', err, id })
);
// Return an object with `abort` function to be used by component
return { abort: () => xhr.abort() };
};
}
Now you can use abort
from your component:
componentDidMount() {
this.requests = [];
this.requests.push(
this.props.dispatch(fetchPost(this.props.postId))
);
}
componentWillUnmount() {
this.requests.forEach(request => request.abort());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With