Interrupt request while navigating from a component in a reactor

I use react, reduxand react-router. One of my pages makes an API request and shows the data. It is working fine. I want to know if the API request is not finished yet, and the user moves to another route, I want him to be able to abort the request.

I guess I should post some action to componentWillUnmount. Just not able to understand how this will work. Sort of...

componentWillUnmount() {
    this.props.dispatch(Actions.abortRequest());
}

And I will save the link xhrsomewhere in action. Not sure if this is the right approach or not (I think not), can someone point me in the right direction?

+4
source share
2

, xhr .
, XMLHttpRequest .

Redux Thunk, - :

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() };     
  };
}

abort :

componentDidMount() {
  this.requests = [];
  this.requests.push(
    this.props.dispatch(fetchPost(this.props.postId))
  );
}

componentWillUnmount() {
  this.requests.forEach(request => request.abort());
}
+8

. , store, - ; xhr , -.

, :

{
  isFetching: false,
  items: [],
  lastUpdated: null
};

isFetching xhr. , xhr , .

+2

Source: https://habr.com/ru/post/1609903/


All Articles