Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abort request while navigating away from the component in React

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?

like image 619
Salman Avatar asked Oct 02 '15 06:10

Salman


People also ask

Which component of react router is used to prompt the user before navigating away from a page?

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.

How do I stop people from leaving my page in react?

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.

How do I stop API call in react?

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.


1 Answers

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());
}
like image 96
Dan Abramov Avatar answered Sep 24 '22 14:09

Dan Abramov